Breaking Down a Dropdown Select List

Filtering display data using a dropdown list is probably the most common method. Let’s break it down and take a look at how it is done.

Here I have a list of events with dates and golf courses. If I want to allow users to see only those events associated with a certain golf course, I undoubtedly need a dropdown list of course names to allow them to pick the one they want to focus on.

Before we can do anything with the selection process, we need to build the content of the list first.

That brings us to the life cycle method of componentDidMount. When this page component is first mounted, we need to prepare the list content properly. In this case, I have a list of all the available courses and related information from the Redux store. The two things we need are the course name to display (c.name) and the id for selection matching purpose (c.id). In order to build a proper selection list for a Semantic UI dropdown component, we need to supply an array of objects that contain three things — key, text, and value. Key is to make each item unique in the list so using the id from the database item will do the job. Text is what is being displayed for each item in the dropdown. Value is the selected value that tells us which item is being selected. After performing a setState, the list is now available for use locally.

In the Dropdown itself, the options now come from the courseList array of objects we prepare in the life cycle method. With this Semantic UI will display a list of course names in dropdown format just like in our first screenshot.

The next key item here is the function we supply for the component when a change is encountered. This is triggered when a user selects a course initially or a different course is selected. Let’s take a look at this function.

When an action is performed on a UI component, we usually receive two items in the triggered function — event and data. The event will be the select action itself while data is what being passed back from the action. In this case, we are only interested in the selected value from the dropdown item. That is why we can do a de-structuring of the data argument and focus only on the { value } element. Since this represents the course id associated with the course selected, we can now perform our filtering based on this id and only display the data items containing this particular id.

Other UI component types can have event driven functions very similar to this one. For example, a checkbox can have a function when the the box is clicked (onClick). The function arguments can be “(e, { clicked })” as we are only concerned about if the box is checked or not (clicked is either true or false).