AppDividend
Latest Code Tutorials

React Select Example | React Dropdown Select | react-select

1

React Select Example is today’s leading topic. We use the library called React-select that features dynamic search/filter, async option loading, accessibility, and fast render times. It has a flexible and beautiful Select Input control for ReactJS with multi-select, autocomplete and ajax support.

It has the following features.

  • Flexible approach to data, with customizable functions.
  • Extensible styling API with emotion.
  • Component Injection API for complete control over the UI behavior.
  • Controllable state props and modular architecture.
  • Long-requested features like option groups, portal support, animation, and more.

React Select Example

Content Overview

Building select elements used to be one of the easiest things to build when working on a web project three or four years ago. Now, there is so much that goes into building select elements especially when UI/UX is a high priority.

Prerequisites

  1. Yarn/npm installed.
  2. A basic understanding of HTML, JavaScript (ES6) and CSS.
  3. A basic understanding of React JS and using create react app.
  4. A basic understanding of the command line terminal.

First, we install the React.js and then install the react-select library.

#Step 1: Install React and other libraries

Type the following command.

npx create-react-app reaselect

React Dropdown Select Example Tutorial

Now, 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 component. First things 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 have created an array that contains the data that needs to be displayed on the dropdown.

After that, we have 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 – allow the user to select multiple values.
  6. isSearchable – allow the user to search for matching options.
  7. name – generate an HTML input with this name, containing the current value.
  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 Example

#Controllable 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 take a 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';

Now, 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 a method that extends 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 in this case are colors like so.

className: In this prop is where we add our bootstrap styling to position our select component away from the top margin as well as centralize our select component nicely. 

#react-select animated components

Let’s take a look at how we can add a little animation to our react select component.

All we need to add animation to our select component is to import the animated component which in this case 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 is used to make us select more than one option at once.

Finally, React Dropdown Select | react-select tutorial is over.

1 Comment
  1. Sajjad Ahmad says

    How do I get the selected value?
    Suppose I want to log the selected value , how do i do that?

Leave A Reply

Your email address will not be published.

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