react

How to use react-select in React


In this article, you will learn about how to use react-select in React

In web projects, Select elements from a select box are widely used and with the help of JavaScript, you may perform this. But now things have been changed and we always want to make the user experience more interactive. To do so, react comes with an amazing NPM package named react-select. Using this package, you can easily style the select elements, add multi-select options, and so on. It is basically a flexible select input control that is used in react. To use this package, first, we need to install it on our local machine. See the below command for installing it.

npm i --save react-select

//or


npm i react-select

After installing this package on our local project, let’s use it and build a simple select-box where we can select a single element.

import Select from 'react-select'
import "./index.css"

function App() {

  const students = [
    { value: 'Alex', label: 'Alex' },
    { value: 'Deven', label: 'Deven' },
    { value: 'Vinicious', label: 'Vinicious' },
  ];
  
    return (
      <div className="container">
        <Select
          options={students}
        />
      </div>
    );
  }
  
export default App;

Here, we simply import the package and use it inside the select tag. Let’s see the output if things are working perfectly or not.

Here, you can see that we are getting a nice and flexible select box and we can select a particular element that we have wanted. Moreover, if you notice, you can see that just write only a few codes. Let’s see another example of it where we will implement multi-select items from a select box.

<Select
   options={students}
   isMulti
 />

Here, all you need to do is to apply isMulti inside the select tag and it will generate a select box from where you can select multiple items. Let’s see the output below:

Here, you can see that we are able to select multiple items from the select box and it gives us a beautiful UI. You can do a lot more cool stuff using this package and these are some examples of it. To get more information on react-select you may visit their official website.


Share on social media

//