AppDividend
Latest Code Tutorials

React Dropdown Select | Create Dropdown Select in React

1

You can use the third-party library like react-select or Building a custom dropdown menu component in React. A dropdown menu consists of four essential components:

  1. header wrapping
  2. header title
  3. list wrapping
  4. list items

What is Dropdown

Dropdowns are toggleable, contextual overlays for displaying lists of links, and more. Like overlays, Dropdowns are built using a third-party library Popper.js, which provides dynamic positioning and viewport detection.

The drop-down menu is a menu that offers a list of options. The title of the menu, or the currently-selected item in the list, is always displayed. When the visible item is clicked, other items from the list “drop-down” into view and the user can choose from those options.

The basic HTML for Bootstrap Dropdown is the following.

<div class="dropdown show">
  <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown link
  </a>

  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

React Select Example

React-select library has 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.

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

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 making 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.

Steps to create React Dropdown Select

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.

Building a custom dropdown menu component in React

Functional components became faster in the latest release of React 16.

However, it is not always possible to take advantage when you need the state definition either in the component or any of the component lifecycle hooks.

For this specific example, it is possible to implement without a state definition or lifecycle hooks, but deploying them makes things more tidy and straightforward.

Using a functional component would require passing some variables as props. When we interact with the dropdown menu, we would be changing these props.

Changing the parent component’s props from a child component requires passing functions from parent to child as props so that you can control the parent component’s state.

In this example, we will use the Functional Component and Class component.

If we just need to have a deal with props, then use the Function component, and if you want to deal with the state, then use the class component.

Let’s create a custom component.

Step 1: Install React and Bootstrap 4

Type the following command to install React 16.

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 a 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 that will be iterated to create a dropdown.

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

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

Our DropDownContent.js component will be 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>
  )
}

In the above code, we have written the HTML code that dynamically creates the dropdown content items using props that comes from the parent component.

This component could also be a class component if you want to select the item and send it to the server because, in that scenario, we have to manage the state of the selected data. But we are not covering this in this tutorial; that is why I have taken this component as a functional component.

Save the file and go to the browser. 

You will see that our react dropdown is working fine.

Finally, React Dropdown Select example is over.

See also

React checkbox example

React Datepicker example

React Bootstrap Modal tutorial

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.