How to create a dropdown in React using react-select
In this article, we will show you how to create a dropdown in React using react-select.
- Flexible approach to data, with customisable functions
- Extensible styling API with emotion
- Component Injection API for complete control over the UI behaviour
- Controllable state props and modular architecture
- Long-requested features like option groups, portal support, animation, and more
- 5 Awesome JavaScript String Tips
- How to detect browser or tab close event in JavaScript
- How to convert XML to JSON in JavaScript
- How to compare two dates in JavaScript
1. Installation
npm i react-select
2. Usage
import React, { useState } from 'react';
import Select from 'react-select';
function App() {
const data = [
{ value: 100, label: "cerulean" },
{ value: 200, label: "fuchsia rose" },
{ value: 300, label: "true red" },
{ value: 400, label: "aqua sky" },
{ value: 500, label: "tigerlily" },
{ value: 600, label: "blue turquoise" }
];
const [selectedOption, setSelectedOption] = useState(null);
// handle onChange event of the dropdown
const handleChange = e => {
setSelectedOption(e);
}
return (
<div className="app">
<h4>Dropdown using react-select <a href="https://codepremix.com">Code Premix</a></h4>
<Select
placeholder="Select Option"
value={selectedOption} // set selected value
options={data} // set list of the data
onChange={handleChange} // assign onChange function
/>
{selectedOption && <div className="output">
<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;