React: Building Dropdown Components

Selecting duplicate values in a dropdown component

Mahesh
JavaScript in Plain English

--

fig(1): building dropdown component

Intro

In this blog, we will build a React component for allowing users to pick values from the dropdown and later tackle the situation when the values are identical. For the sake of keeping the blog simple, the data set is hard coded in the component but in your case, you might fetch these data from an API or receive them as props.

Motivation

Our SPA allowed users to copy content between different groups, and sub-group however if the sub-group has the same content title, then our dropdown always defaulted to the first value from the list. This prevented users from copying the second content. The possible solutions were:

  • Do not allow users to create content with the same content title
  • Do not display duplicate content titles again
  • Allow users to pick the content with the same title without any problem

Data

Design

fig(2): dropdown data flow design

Code

First, we will focus on building components responsible for listing data and allowing users to select interested values. In a later section, we will modify the same component to handle duplicate values.

Feel free to replace code-sandbox code with the above code to replicate the issue. If you do then we can see the user cannot select a second duplicated value (i.e Math Problems).

fig(3): listing data in dropbox with duplicates [issue replication]

Updated code to handle duplicate values:

Here is the complete example in codesandbox.

Bonus: We could take the extra step and extract the dropdown logic to its own component so that it can be published in the reusable component library.

My previous three blogs:
1. React: SPA with path-based routing in AWS Cloud
2. React: Search Component Design
3. React | Node: Why should we care about dependencies?

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, and Discord.

--

--