Implement dropdown in ReactJS
Today we will show you how to implement dropdown in ReactJS. We will use the npm package to implement dropdown. Start from scratch and later on show you more features related to dropdown.
Building a custom dropdown menu component for React, Create a Dropdown Menu using ReactJS, react js dropdown selected value, how to make a drop down list in react, react bootstrap dropdown button, bind dropdown in react js, Create a Dropdown in React that Closes When the Body is Clicked, How to get selected value of a dropdown menu in ReactJS.
Checkout more articles on ReactJS
- Navigate from one page to another page in ReactJS
- Search filter for multiple object in ReactJS
- Add or remove input fields dynamically with ReactJS
- Add Multiple Custom Markers to Google Maps in ReactJS
- Google Cloud SDK installation failed on Windows
https://youtu.be/mhLVjY09FOc
Way to implement dropdown in ReactJS
1. Create react application
Let’s start by creating a simple react application with the help of the create-react-app. If you don’t know how to create a react application then refer to the link below.
2. Install npm dropdown package
In order to implement dropdown, we need to install `react-select` npm package in the project. Use the below command to install it.
npm i react-select
3. Implement the dropdown
First, start with the design where we will use the `react-select` npm package for dropdown and variable to store/display selected option.
Following attributes are used to implement the dropdown.
- placeholder - Display the placeholder in dropdown
- value - Display selected value of the dropdown
- options - Pass the list of data to display records in dropdown menu items.
- onChange - Assign the onChange event of the dropdown to get the selected value.
App.js
import React, { useState } from 'react';
import Select from 'react-select';
function App() {
const data = [
{
value: 1,
label: "cerulean"
},
{
value: 2,
label: "fuchsia rose"
},
{
value: 3,
label: "true red"
},
{
value: 4,
label: "aqua sky"
},
{
value: 5,
label: "tigerlily"
},
{
value: 6,
label: "blue turquoise"
}
];
const [selectedOption, setSelectedOption] = useState(null);
// handle onChange event of the dropdown
const handleChange = e => {
setSelectedOption(e);
}
return (
<div className="App">
<a href="https://www.cluemediator.com">Clue Mediator</a><br /><br />
<Select
placeholder="Select Option"
value={selectedOption} // set selected value
options={data} // set list of the data
onChange={handleChange} // assign onChange function
/>
{selectedOption && <div style={{ marginTop: 20, lineHeight: '25px' }}>
<b>Selected Option</b><br />
<div style={{ marginTop: 10 }}><b>Label: </b> {selectedOption.label}</div>
<div><b>Value: </b> {selectedOption.value}</div>
</div>}
</div>
);
}
export default App;
4. Output
Implement dropdown in ReactJS - Clue Mediator
That's it for today.
Thank you for reading. Happy Coding!