React Dropdown Select Tutorial with react-select

To create a dropdown, you can use the “react-select” library. The react-select library has features like dynamic search/filter, async option loading, accessibility, and fast render times. In addition, it has a flexible and beautiful Select Input control for ReactJS with multi-select, autocomplete, and Ajax support.

Here are the steps to create a dropdown select in React.js:

Step 1: Install React and other libraries

npx create-react-app reaselect

React Dropdown Select Example Tutorial

Go inside the project folder.

cd reaselect

To install React-Select v2, add the react-select package using the following command.

yarn add react-select

# or

npm install react-select --save

Custom styling your react components

We can add beauty and aesthetics to our select components. First, we will leverage Bootstrap CSS to resize our select component so it doesn’t take up the whole width of the web page. 

 Type the following command install Bootstrap 4 using the following command.

yarn add bootstrap

# or

npm install bootstrap --save

With Bootstrap installed, we’ll add our styling to our select component.

Step 2: Import the react-select module.

Inside the src >> App.js file, add the following code.

// App.js

import React from 'react';
import Select from 'react-select';
import 'bootstrap/dist/css/bootstrap.min.css';

const techCompanies = [
  { label: "Apple", value: 1 },
  { label: "Facebook", value: 2 },
  { label: "Netflix", value: 3 },
  { label: "Tesla", value: 4 },
  { label: "Amazon", value: 5 },
  { label: "Alphabet", value: 6 },
];

const App = () => (
  <div className="container">
    <div className="row">
      <div className="col-md-4"></div>
      <div className="col-md-4">
        <Select options={ techCompanies } />
      </div>
      <div className="col-md-4"></div>
    </div>
  </div>
);

export default App

React Select Dropdown example

Here, we have imported the bootstrap 4 and react-select library.

Then, we created an array containing the data that needs to be displayed on the dropdown.

After that, we used the Select element and pass the options object. There are many other properties available, which are the following.

  1. autofocus – focus the control when it mounts.
  2. className – apply a className to the control.
  3. classNamePrefix – apply classNames to inner elements with the given prefix.
  4. isDisabled – disable the control.
  5. isMulti – Allows the user to select multiple values.
  6. isSearchable – Allows the user to search for matching options.
  7. name – Generate an HTML input containing the current value with this name.
  8. onChange – subscribe to change events.
  9. options – specify the options the user can select from.
  10. placeholder – change the text displayed when no option is selected.
  11. value – control the current value.

You must import the Select component from react-select.

Each object in the options array techCompanies must have at least two values: label, a string, and value, which may be any type. The only required prop is the options array.

Other Features

We can use the multiple select using the following property. We need to add that property.

<Select options={ techCompanies } 
          isMulti />

 

React Multi Select ExampleControllable Props in React

You can control the following props by providing values for them. If you don’t, the react-select will manage them for you.

  • value / onChange – specify the current value of the control.
  • menuIsOpen / onMenuOpen / onMenuClose – control whether the menu is open.
  • inputValue / onInputChange – control the value of the search input (changing this will update the available options).

If you don’t provide these props, you can set the initial value of the state they control:

  • defaultValue – set the initial value of the control.
  • defaultMenuIsOpen – set the initial open value of the menu.
  • defaultInputValue – set the initial value of the search input.

Methods

React-select exposes two public methods:

  • focus() – focus the control programmatically.
  • blur() – blur the control programmatically.

Custom react-select components

Under styles and states, we discussed two custom components (option and control), which we used to extend the select styling.

In this section, we’ll look at another custom component called the Custom SingleValue. This custom component does what our regular select component does, but we’re going to add a little bit of finesse.

In our App.js file, we’ll import the React and Select packages from the react.js and react-select, respectively, like so:

// App.js

import React, { type ElementConfig } from 'react';
import Select, { components } from 'react-select';

Write the following code inside the App.js file.

// App.js

import React, { type ElementConfig } from 'react'; 
import Select, { components } from 'react-select';
 
 const SingleValue = ({ children, ...props }) => (
   <components.SingleValue {...props}>
     {children}
   </components.SingleValue>
 );
 
 class App extends React.Component {
   state = {};
   state = {
     selectedOption: null,
   }
   handleChange = (selectedOption) => {
     this.setState({ selectedOption });
   }
   render() {
     return (
       <Select
           className="mt-4 col-md-6 col-offset-4"
           onChange={this.handleChange}
           styles={{ singleValue: (base) => ({ ...base, padding: 5, borderRadius: 5, background: this.state.selectedOption.value, color: 'white', display: 'flex' }) }}
           components={{ SingleValue }}
           options={colourOptions}
         />
     );
   }
 }
 export default App;

In the above code, we define our custom component SingleValue as extending the base component in the react-select package.

In our App class, we have a couple of props and functions which contribute to the functionality (as shown in the image above), such as:

handleChange: This method is triggered by a state manager prop called the onChange. This method is responsible for storing the value of the selected option in our state object called selectedOption

styles: In this prop, we extend the style modifier method singleValue, where we modify the styling already accessible to us by default by spreading default styles into the base object. The line responsible for adding a background color to each selected option is the background: this.state.selectedOption.value, where we get the current option selected from the state and use it to update the background

components: In the component prop, we pass in the SingleValue component, the primary function of the component is to display in the input for a single select.

options: The options prop that we all know by now is how we pass in our array object of select items, which are colors like so.

className: In this prop, we add our bootstrap styling to position our select component away from the top margin and centralize our select component nicely. 

React-select animated components

We need to add animation to our select component to import the animated component, which is named makeAnimated and then reference makeAnimated in our component’s props like the following.

// App.js

import React from 'react';
import Select, { components } from 'react-select';
import makeAnimated from 'react-select/lib/animated';
import 'bootstrap/dist/css/bootstrap.css';

const colourOptions = [] //our array of colours

class App extends React.Component {
  render(){
    return (
      <Select
        className="mt-4 col-md-6 col-offset-4"
        components={makeAnimated()}
        isMulti
        options={colourOptions}
        />
    );
  }
}

export default App;

You can use the isMulti prop to make us select more than one option at once.

Creating a custom dropdown menu component in React

Step 1: Install React and Bootstrap 4

npx create-react-app dropdown

Now, install Bootstrap 4.

yarn add bootstrap

Step 2: Create parent and child components

The next step is to create a folder inside the src folder and name the folder components.

Inside the components, create the following two files.

  1. DropDown.js(Parent component)
  2. DropDownContent.js(Child component)

A parent component holds single or multiple dropdown menus, and since each dropdown menu has unique content, we need to parameterize it by passing information as props.

Write the following code inside the App.js file.

// App.js

import React from 'react';

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';

import { DropDown } from './components/DropDown'; 

function App() {
  return (
    <div className="container">
      <DropDown />
    </div>
  );
}

export default App;

From the code, you can see that we have imported the DropDown component we just created.

Now, write the following code inside the DropDown.js file.

import React, { Component } from 'react';
import { DropDownContent } from './DropDownContent';

export class DropDown extends Component {

  constructor() {
    super()
    this.state = {
      name: [
        {
          id: 0,
          title: 'Stranger Things',
          selected: false,
          key: 'name'
        },
        {
          id: 1,
          title: 'Money Heist',
          selected: false,
          key: 'name'
        },
        {
          id: 2,
          title: 'Rick and Morty',
          selected: false,
          key: 'name'
        },
        {
          id: 3,
          title: 'Ozark',
          selected: false,
          key: 'name'
        },
        {
          id: 4,
          title: 'Altered Carbon',
          selected: false,
          key: 'name'
        },
        {
          id: 5,
          title: 'Dark',
          selected: false,
          key: 'name'
        }
      ]
    }
  }

  render() {
    return (
      <div>
        <DropDownContent
        title="Select Series"
        list={this.state.name} />
      </div>
    )
  }
}

In this code, we have defined the data iterated to create a dropdown.

Then pass the two properties in the child component via props.

This is the class component because we have to manage the data via the state.

Our DropDownContent.js component will be a functional component because it deals with only props, and there is no need to use state because there is no state to maintain.

import React from 'react';

export function DropDownContent(props) {
  return (
    <div className="dropdown">
        <button className="btn btn-primary dropdown-toggle"
          type="button"
          data-toggle="dropdown">
          {props.title}
        </button>
        {<div className="dropdown-menu">
          {props.list.map((item) => (
            <a className="dropdown-item" key={item.id} href="/">{item.title}</a>
          ))}
        </div>}
      </div>
  )
}

That’s it.

1 thought on “React Dropdown Select Tutorial with react-select”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.