You can use a third-party library like react-select or build a custom dropdown menu component in React. A dropdown menu consists of four essential components:
- header wrapping
- header title
- list wrapping
- list items
What is Dropdown
Dropdowns are toggleable, contextual overlays for displaying lists of links, and more. Like overlays, Dropdowns are built using a third-party library, Popper.js, which provides dynamic positioning and viewport detection.
The dropdown menu is a menu that offers a list of options. The title of the menu, or the currently-selected item in the list, is always displayed. When the visible item is clicked, other items from the list “dropdown” into view, and the user can choose from those options.
The basic HTML for Bootstrap Dropdown is the following.
<div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown link </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </div>
React dropdown select
To create a dropdown select in React, use the react-select library. The react-select library has features dynamic search/filter, async option loading, accessibility, and fast render times. In addition, it has a flexible and beautiful Select Input control for ReactJS with multi-select, autocomplete, and ajax support.
react-select features
It has the following features.
- Flexible approach to data, with customizable functions.
- Extensible styling API with emotion.
- Component Injection API for complete control over the UI behavior.
- Controllable state props and modular architecture.
- Long-requested features like option groups, portal support, animation, and more.
Building select elements used to be one of the easiest things to build when working on a web project three or four years ago. Now, so much goes into making select elements, especially when UI/UX is a high priority.
Prerequisites
- Yarn/npm installed.
- A basic understanding of HTML, JavaScript (ES6), and CSS.
- A basic understanding of React JS and using create react app.
- A basic understanding of the command line terminal.
Steps to create React Dropdown Select
First, we install the React.js and then install the react-select library.
Step 1: Install React and other libraries
Type the following command.
npx create-react-app reaselect
Now, go inside the project folder.
cd reaselect
To install React-Select v2, add the react-select package using the following command.
yarn add react-select # or npm install react-select --save
#Custom styling your react components
We can add beauty and aesthetics to our select components. First things first, we will leverage bootstrap CSS to resize our select component, so it doesn’t take up the whole width of the web page.
Type the following command, install Bootstrap 4 using the following command.
yarn add bootstrap # or npm install bootstrap --save
With bootstrap installed, we’ll add our styling to our select component.
Step 2: Import the react-select module.
Inside the src >> App.js file, add the following code.
// App.js import React from 'react'; import Select from 'react-select'; import 'bootstrap/dist/css/bootstrap.min.css'; const techCompanies = [ { label: "Apple", value: 1 }, { label: "Facebook", value: 2 }, { label: "Netflix", value: 3 }, { label: "Tesla", value: 4 }, { label: "Amazon", value: 5 }, { label: "Alphabet", value: 6 }, ]; const App = () => ( <div className="container"> <div className="row"> <div className="col-md-4"></div> <div className="col-md-4"> <Select options={ techCompanies } /> </div> <div className="col-md-4"></div> </div> </div> ); export default App
Here, we have imported the bootstrap 4 and react-select library.
Then, we created an array containing the data that needs to be displayed on the dropdown.
After that, we have used the Select element and pass the options object. There are many other properties available, which are the following.
- autofocus – focus the control when it mounts.
- className – apply a className to the control.
- classNamePrefix – apply classNames to inner elements with the given prefix.
- isDisabled – disable the control.
- isMulti – allow the user to select multiple values.
- isSearchable – allow the user to search for matching options.
- name – generate an HTML input containing the current value with this name.
- onChange – subscribe to change events.
- options – specify the options the user can select from.
- placeholder – change the text displayed when no option is selected.
- value – control the current value.
You must import the Select component from react-select.
Each object in the options array techCompanies must have at least two values: label, a string, and value, which may be any type.
The only required prop is the options array.
Other Features
We can use the multiple select using the following property. We need to add that property.
<Select options={ techCompanies } isMulti />
Controllable Props in React
You can control the following props by providing values for them. If you don’t, the react-select will manage them for you.
- value / onChange – specify the current value of the control.
- menuIsOpen / onMenuOpen / onMenuClose – control whether the menu is open.
- inputValue / onInputChange – control the value of the search input (changing this will update the available options).
If you don’t provide these props, you can set the initial value of the state they control:
- defaultValue – set the initial value of the control.
- defaultMenuIsOpen – set the initial open value of the menu.
- defaultInputValue – set the initial value of the search input.
Methods
React-select exposes two public methods:
- focus() – focus the control programmatically.
- blur() – blur the control programmatically.
Custom react-select components
Under styles and states, we discussed two custom components (option and control), which we used to extend the select styling.
In this section, we’ll look at another custom component called the Custom SingleValue. This custom component does what our regular select component does, but we’re going to add a little bit of finesse.
In our App.js file, we’ll import the React and Select packages from the react.js and react-select, respectively like so:
// App.js import React, { type ElementConfig } from 'react'; import Select, { components } from 'react-select';
Now, write the following code inside the App.js file.
// App.js import React, { type ElementConfig } from 'react'; import Select, { components } from 'react-select'; const SingleValue = ({ children, ...props }) => ( <components.SingleValue {...props}> {children} </components.SingleValue> ); class App extends React.Component { state = {}; state = { selectedOption: null, } handleChange = (selectedOption) => { this.setState({ selectedOption }); } render() { return ( <Select className="mt-4 col-md-6 col-offset-4" onChange={this.handleChange} styles={{ singleValue: (base) => ({ ...base, padding: 5, borderRadius: 5, background: this.state.selectedOption.value, color: 'white', display: 'flex' }) }} components={{ SingleValue }} options={colourOptions} /> ); } } export default App;
In the above code, we define our custom component SingleValue as extending the base component in the react-select package.
In our App class, we have a couple of props and functions which contribute to the functionality (as shown in the image above), such as:
handleChange: This method is triggered by a state manager prop called the onChange. This method is responsible for storing the value of the selected option in our state object called selectedOption
styles: In this prop, we extend the style modifier method singleValue, where we modify the styling already accessible to us by default by spreading default styles into the base object. The line responsible for adding a background color to each selected option is the background: this.state.selectedOption.value where we get the current option selected from the state and use it to update the background
components: In the component prop, we pass in the SingleValue component, the primary function of the component is to display in the input for a single select.
options: The options prop that we all know by now is how we pass in our array object of select items, which are colors like so.
className: In this prop, we add our bootstrap styling to position our select component away from the top margin and centralize our select component nicely.
React-select animated components
Let’s look at how we can add a little animation to our react select component.
We need to add animation to our select component to import the animated component, which is named makeAnimated, and then reference makeAnimated in our component’s props like the following.
// App.js import React from 'react'; import Select, { components } from 'react-select'; import makeAnimated from 'react-select/lib/animated'; import 'bootstrap/dist/css/bootstrap.css'; const colourOptions = [] //our array of colours class App extends React.Component { render(){ return ( <Select className="mt-4 col-md-6 col-offset-4" components={makeAnimated()} isMulti options={colourOptions} /> ); } } export default App;
You can use the isMulti prop to make us select more than one option at once.
Building a custom dropdown menu component in React
Functional components became faster in the latest release of React 16.
However, it is not always possible to take advantage when you need the state definition either in the component or any component lifecycle hooks.
It is possible to implement this specific example without a state definition or lifecycle hooks, but deploying them makes things more tidy and straightforward.
Using a functional component would require passing some variables as props. Therefore, when we interact with the dropdown menu, we will be changing these props.
Changing the parent component’s props from a child component requires passing functions from parent to child as props so that you can control the parent component’s state.
In this example, we will use the Functional Component and Class component.
If we need to deal with props, use the Function component, and if you want to deal with the state, use the class component.
Let’s create a custom component.
Step 1: Install React and Bootstrap 4
Type the following command to install React 16.
npx create-react-app dropdown
Now, install Bootstrap 4.
yarn add bootstrap
Step 2: Create parent and child components
The next step is to create a folder inside the src folder and name the folder components.
Inside the components, create the following two files.
- DropDown.js(Parent component)
- DropDownContent.js(Child component)
A parent component holds single or multiple dropdown menus, and since each dropdown menu has unique content, we need to parameterize it by passing information as props.
Write the following code inside the App.js file.
// App.js import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/js/bootstrap.bundle.min.js'; import { DropDown } from './components/DropDown'; function App() { return ( <div className="container"> <DropDown /> </div> ); } export default App;
From the code, you can see that we have imported the DropDown component we just created.
Now, write the following code inside the DropDown.js file.
import React, { Component } from 'react'; import { DropDownContent } from './DropDownContent'; export class DropDown extends Component { constructor() { super() this.state = { name: [ { id: 0, title: 'Stranger Things', selected: false, key: 'name' }, { id: 1, title: 'Money Heist', selected: false, key: 'name' }, { id: 2, title: 'Rick and Morty', selected: false, key: 'name' }, { id: 3, title: 'Ozark', selected: false, key: 'name' }, { id: 4, title: 'Altered Carbon', selected: false, key: 'name' }, { id: 5, title: 'Dark', selected: false, key: 'name' } ] } } render() { return ( <div> <DropDownContent title="Select Series" list={this.state.name} /> </div> ) } }
In this code, we have defined the data iterated to create a dropdown.
Then pass the two properties in the child component via props.
This is the class component because we have to manage the data via the state.
Our DropDownContent.js component will be a functional component because it deals with only props, and there is no need to use state because there is no state to maintain.
import React from 'react'; export function DropDownContent(props) { return ( <div className="dropdown"> <button className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> {props.title} </button> {<div className="dropdown-menu"> {props.list.map((item) => ( <a className="dropdown-item" key={item.id} href="/">{item.title}</a> ))} </div>} </div> ) }
We have written the HTML code in the above code that dynamically creates the dropdown content items using props from the parent component.
This component could also be a class component if you want to select the item and send it to the server because, in that scenario, we have to manage the state of the selected data. But we are not covering this in this tutorial; I have taken this component as a functional component.
Save the file and go to the browser.
You will see that our react dropdown is working fine.
That’s it for this demo tutorial.
How do I get the selected value?
Suppose I want to log the selected value , how do i do that?