React-select In React

Hello developers, In this blog we are going to learn how we can use react-select component instead of simple HTML select tag

First, create a new app :

npx create-react-app react-select

then install react-select using following command :

npm i --save react-select 
or
yarn add react-select

then create an object which includes value and label

Note: value and label keys are required for react-select

const ages = [
   { value: "15", label: "15", isDisabled: true }, isDisabled key is required if you want to disable particular option 
   { value: "20", label: "20" },
   { value: "25", label: "25" },
 ];

then import react-select and use it :

<Select options={ages} isOptionDisabled={(opt) => opt.isDisabled} />

isOptionDisabled is used to disable a particular option, here in my code option age 15 is disabled

If you want to select multiple option then add isMulti prop to Select component

You can add isClearable to clear all selected value

add closeMenuOnSelect-{false} to prevent menu from closing while selecting multiple options

<Select options={ages} isOptionDisabled={(opt) => opt.isDisabled} isMulti isClearable closeMenuOnSelect={false}/>

Demo:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories