How to Use react-select in React Application?
Last Updated :
26 Jun, 2024
React Select is a flexible and handy dropdown library for React that handles multi-select, loading data asynchronously, custom options, and more in your components with ease. In this article, we will see how to use react-select in React Application.
Prerequisite
Approach
To implement react-select, follow these steps:
- Install the react-select library.
- Create a React component that uses react-select.
- Manage the state for the selected option(s).
- Style the component for a better user experience.
Create React App and Project Structure
Step 1: Create a React App.
Open your terminal and run.
npx create-react-app <-Project-Name->
cd <-Project-Name->
Step 2: Install react-select.
npm install react-select
Updated Dependencies
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"react-select": "^5.8.0",
"web-vitals": "^2.1.4"
},
Project Structure
Folder SrtuctureExample: This illustrates a custom React component "ReactSelect", styling it with CSS, and then integrating it into the main "App.js" file.
CSS
/*ReactSelect.css*/
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #5a5a5a;
}
.select-container {
width: 300px;
padding: 20px;
background: rgb(143, 143, 143);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
text-align: center;
margin-top: 100px;
}
.select-wrapper {
margin-top: 20px;
}
.Select__control {
width: 200px;
margin: 0 auto;
}
.selected-value {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
h2 {
font-size: 20px;
margin-bottom: 10px;
}
p {
font-size: 16px;
margin: 0;
}
JavaScript
// ReactSelect.js component
import React, { useState } from 'react';
import Select from 'react-select';
import './ReactSelect.css';
const carBrands = [
{ value: 'toyota', label: 'Toyota' },
{ value: 'honda', label: 'Honda' },
{ value: 'ford', label: 'Ford' },
{ value: 'bmw', label: 'BMW' },
{ value: 'audi', label: 'Audi' }
];
function ReactSelect() {
const [selectedCar, setSelectedCar] = useState(null);
const handleChange = (selectedOption) => {
setSelectedCar(selectedOption);
};
return (
<div className="select-container">
<h1>ReactSelect</h1>
<div className="select-wrapper">
<Select
options={carBrands}
onChange={handleChange}
placeholder="Select a car brand..."
className="select-input"
/>
</div>
{
selectedCar && (
<div className="selected-value">
<h2>Selected Car Brand:</h2>
<p>{selectedCar.label}</p>
</div>
)}
</div>
);
}
export default ReactSelect;
JavaScript
//App.js
import React from 'react';
import './App.css';
import ReactSelect from './components/ReactSelect';
function App() {
return (
<div className="App">
<ReactSelect />
</div>
);
}
export default App;
Output:
ReactSelect Component