HomeBlogLearn to create a Dropdown Select Menu Component in React

Learn to create a Dropdown Select Menu Component in React

Learn to create a Dropdown Select Menu Component in React

Hello there, I have made a Dropdown Select Menu in React. In this tutorial, I will teach you How to create a custom Dropdown Select Menu in React Js.

You may already know about the select element in regular HTML, It creates a dropdown select menu. Inside select we use the option element to define the menu options, as in the below example:

Basic Dropdown Select Menu in HTML

html
<select id="fruits"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> <option value="grape">Grape</option> <option value="pear">Pear</option> </select>

This is known as a basic method of implementing a Dropdown Select Menu in HTML.

As I have said it's a basic method, a basic method in the sense not about its functionality it's about the design, user experience, user-friendly, etc.

So, Here I will teach you and explain to you how to create a Dropdown Select Menu in React, without using select elements. Let's continue.

Learn: How to create a Dropdown Select Menu in React JS?

We will walk through the process of creating a dropdown select menu in React JS step by step, by making a country name selection dropdown menu.

Prerequisites

Before we dive into the implementation, make sure you have a basic understanding of ReactJs.

Step 1: Set up your project by creating a new React app

First, you go inside any directory in your system and create a new React app by using the create-react-app command.

properties
npx create-react-app dropdown-select-menu

Then go to dropdown-select-menu folder by running this command

properties
cd dropdown-select-demo

Then run your React App

properties
npm start

Step 2: Create a basic structure using the Functional Component 

In your project, navigate to the src folder, then go to the root component App.js in this file React provides you with some code by default. Delete all the code here.

Then create the basic structure of the Dropdown Select Menu, as in the below code example:

jsx
import "./App.css"; import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; function App() { return ( <div className="App"> <div className="selectOption"> <input type="text" placeholder="Select Your Country" readOnly /> <span className="icon"> <FontAwesomeIcon icon={["fas", "angle-down"]} /> </span> <div className="options"> <li></li> </div> </div> </div> ); } export default App;

Here, first, import the App.css file, to apply CSS styles to this component.

Then import the FontAwesomeIcon component from the @fortawesome/react-fontawesome library. This component is used to display icons from the FontAwesome icon library in your React application.

Read also: CSS Gradient Border Glowing Animation Hover Effect

To use @fortawesome library you need to first install it in your project. So, install these following packages by using npm

properties
npm i --save @fortawesome/fontawesome-svg-core npm install --save @fortawesome/free-solid-svg-icons npm install --save @fortawesome/react-fontawesome

After installing these packages first go to the index.js file, here you have to import the library object and icons as given example below:

jsx
import { library } from "@fortawesome/fontawesome-svg-core"; import { faAngleDown } from "@fortawesome/free-solid-svg-icons";

As you can see in the above example,

  • The library object is imported from @fortawesome/fontawesome-svg-core and
  • The faAngleDown icon is imported from @fortawesome/free-solid-svg-icons

Then add the imported icon (faAngleDown) to the library like this:

jsx
library.add(faAngleDown);

Now you can use this icon in any component throughout your application without the need to import them individually in each component. For more details you can read React FontAwesome Docs

Then inside the return statement add the JSX code to create the basic structure.

In the JSX:

  • <div className="App">: This div element serves as the main container for the entire component.
  • <div className="selectOption">: This div element represents the container for the custom select input.
  • <input type="text" placeholder="Select Your Country" readOnly/>: This is an <input> element of type “text”. It acts as a text input field where users can input or select a country. The placeholder attribute provides a hint or prompt to the user (“Select Your Country”), and the readOnly attribute indicates that the input field is not editable by the user.
  • <span className="icon">: This span element is used to hold the dropdown icon.
  • <FontAwesomeIcon icon={["fas", "angle-down"]} />: This seems to use the FontAwesomeIcon component from a library @fortawesome/react-fontawesome to display an icon. The icon prop specifies the icon to be displayed, in this case, the “angle-down” icon from the Font Awesome icon set.
  • <div className="options">: This div element is the container for the dropdown options.
  • <li></li>: This li element is for the actual dropdown options. Basically, here we will use the array map() method to render each option dynamically as li elements. We will do it further.

Step 3: Add functionality and logic

After creating the basic structure of the dropdown select menu in React, let's add the functionality,

First import the useState and useRef hooks which will be used for managing component state and creating a reference to a DOM element. Like this:

jsx
import React, { useState, useRef } fromreact”;

Then create an Array called optionsArray contains a list of country names.

jsx
const optionsArray = [ "India", "United States", "United Kingdom", "japan", "Canada", "Germany", ];

After creating this array, inside the div element whose class name is options, we will use a map() function to iterate over each item of optionsArray and render a corresponding <li> element for each option. Like this:

jsx
<div className="options"> {optionsArray.map((item, index) => ( <li key={index}>{item}</li> ))} </div>

Then create a state variable named openselect and a setter function setOpenSelect using the useState hook.

Open/Close Dropdown Select Menu in React JS

This functionality is for when users click on the input element the dropdown menu will open or its state change to true and when the user clicks outside the dropdown menu it will be closed or its state change to false.

jsx
const [openselect, setOpenSelect] = useState(false);

The initial state openselect is false. This state is used to control whether the dropdown options are displayed or not.

We use the useRef hook** to create a reference object called inputRef.

jsx
const inputRef = useRef();

Add this inputRef object using ref attribute into the input element, Like this:

html
<input ref="{inputRef}" type="text" placeholder="Select Your Country" readonly />;

This reference will be used to directly manipulate the input element representing the selected option in the custom dropdown select menu in react.

Update the dropdown select menu selected value on the selection.

Then create an event handler function called selectValue, like this:

jsx
function selectValue(e) { inputRef.current.value = e.target.outerText; setOpenSelect(false); }

The selectValue function for handling the selection of an option from the dropdown. When an option ( li element ) is clicked, this function sets value of the input element (using inputRef) to the text content of the clicked option or li element text value.

Additionally, it closes the dropdown by setting openselect to false. So that, after selecting the option or clicking on the li element the dropdown menu will be closed.

So add this function into the li element using the onClick attribute, like this:

jsx
{ optionsArray.map((item, index) => ( <li onClick={selectValue} key={index}> {item} </li> )); }

Then, create another event handler function named openOption

jsx
function openOption() { setOpenSelect(true); }

Add this openOption function into the input element using the onClick attribute, like this:

jsx
<input onClick={openOption} onBlur={() => { setOpenSelect(false); }} ref={inputRef} type="text" placeholder="Select Your Country" readOnly />

The openOption function is triggered when the input element is clicked. It opens the dropdown by updating the state of openselect to true.

Also as you can see onBlur={() => { setOpenSelect(false); }}: This attribute attaches an anonymous arrow function to the onBlur event of the <input> element.

The onBlur event occurs when the element loses focus, it means when the user clicks outside the input element, this function is invoked, updating the state of openselect to false. So the dropdown will be closed.

After doing all these things, The <div> the element whose class name we defined options, change its className to className={openselect ? "options active" : "options"} As you can see this is a conditional expression.

The condition is used to determine the class name. If openselect is true, the class "options active" will be applied, and when active is applied the options menu will be open (We will implement it in the CSS part) otherwise, if openselect is false, the class options will be applied.

Secondly, The <div> the element whose class name we defined icon, also change its className to className={openselect ? "icon active" : "icon"} Here we have also added an active class for active styling based on the value of the openselect state.

So, finally, the full code of our App.js functional root component is given below:

jsx
import "./App.css"; import React, { useState, useRef } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; function App() { const optionsArray = [ "India", "United States", "United Kingdom", "japan", "Canada", "Germany", ]; const [openselect, setOpenSelect] = useState(false); const inputRef = useRef(); function selectValue(e) { inputRef.current.value = e.target.outerText; setOpenSelect(false); } function openOption() { setOpenSelect(true); } return ( <div className="App"> <div className="selectOption"> <input onClick={openOption} onBlur={() => { setOpenSelect(false); }} ref={inputRef} type="text" placeholder="Select Your Country" readOnly /> <span className={openselect ? "icon active" : "icon"}> <FontAwesomeIcon icon={["fas", "angle-down"]} /> </span> <div className={openselect ? "options active" : "options"}> {optionsArray.map((item, index) => ( <li onClick={selectValue} key={index}> {item} </li> ))} </div> </div> </div> ); } export default App;

Step 4: Styling the component using CSS

Then we will add the styles by writing CSS in App.css file. I have given the CSS code below you can copy it and use it:

css
.App { width: 100%; height: 100vh; background-color: #0a0a0a; display: flex; justify-content: center; align-items: center; } .selectOption { position: relative; width: 350px; height: auto; display: flex; } input { position: relative; width: 100%; padding: 20px; outline: none; border: none; border-radius: 10px; font-size: 20px; background: rgb(21, 21, 21); color: white; cursor: pointer; } .icon { position: absolute; right: 8%; top: 50%; transform: translateY(-50%) rotate(-90deg); font-size: 25px; color: rgb(208, 208, 208); display: flex; align-items: center; padding-top: 5px; transition: transform 0.2s ease; pointer-events: none; } .icon.active { transform: translateY(-50%) rotate(0deg); } .options { position: absolute; width: 100%; max-height: 220px; background: #101010; border-radius: 10px; top: 100%; transform: translateY(0); overflow: hidden; overflow-y: auto; visibility: hidden; opacity: 0; transition: 0.3s ease; color: #c9c9c9; } .options.active { visibility: visible; opacity: 1; transform: translateY(5%); } li { list-style: none; font-size: 17px; text-transform: capitalize; padding: 17px 20px; cursor: pointer; } li:hover { background: #242424; } /* width */ ::-webkit-scrollbar { width: 10px; } /* Track */ ::-webkit-scrollbar-track { background: #3b3b3b; } /* Handle */ ::-webkit-scrollbar-thumb { background: #d9d9d9; border-radius: 20px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #8e8e8e; }

Conclusion

Finally, we have completed our project and successfully built the Dropdown Select Menu in React JS. You can use this custom Dropdown Select Menu in your personal project and freelance project as well. Happy Coding 😀

Read also the viral blog: Email Input Validation using HTML, CSS, & JavaScript