How to usereact-select component in ReactJS
In this approach we will use a third-party library react-select to set selected option .react-select offers enhanced functionality and styling options compared to native <select> elements.
Example: This example uses react-select component to set the option of a select in React.
import React, { useState } from 'react';
import Select from 'react-select';
const App = () => {
const countries = [
{ value: "0", label: "Select Country" },
{ value: "1", label: "USA" },
{ value: "2", label: "India" },
{ value: "3", label: "Japan" },
{ value: "4", label: "Mexico" }
];
const [selectedOption, setSelectedOption] = useState(countries[0]);
const handleChange = (option) => {
setSelectedOption(option);
};
return (
<div>
<div style={{ marginBottom: '10px' }}>
<h3>Welcome to w3wiki</h3>
<Select
value={selectedOption}
onChange={handleChange}
options={countries}
/>
</div>
<div style={{ fontWeight: 'bold' }}>
Selected Option:
<span style={{ color: '#007bff' }}>
{selectedOption.label}
</span>
</div>
</div>
);
};
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project
npm start
Output:
How to Set Selected Option of a Select in React?
In the React setting the selected option of a Select can be achieved using different approaches including using the native HTML <select> element and using third-party select components like react-select.
We will discuss two approaches to Setting selected options of a select in React:
Table of Content
- Using the native ‘select’ element
- Using react-select component