react select npm
import React from 'react'; import Select from 'react-select'; const options = [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' }, ]; class App extends React.Component { state = { selectedOption: null, }; handleChange = selectedOption => { this.setState({ selectedOption }); console.log(`Option selected:`, selectedOption); }; render() { const { selectedOption } = this.state; return ( ); } }
Here is what the above code is Doing:
1. We’re importing the Select component from react-select.
2. We’re creating an array of options for our select field.
3. We’re creating a state variable called selectedOption.
4. We’re creating a handleChange function that will update the selectedOption state variable.
5. We’re rendering a Select component.
6. We’re passing the selectedOption state variable to the value prop.
7. We’re passing the handleChange function to the onChange prop.
8. We’re passing the options array to the options prop.