Open In App

DropDown OnChange Event Using ReactJS

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The DropDown OnChange event in ReactJS is an important functionality that allows developers to respond to changes made to a dropdown menu.

This event is triggered when the user selects a new option from the dropdown list. In this article, we will learn how to use onChange event in DropDown menu.

Prerequisites

Steps to Create DropDown OnChange Event

Step 1: You will start a new project using create-react-app command

npx create-react-app dropdown-menu

Step 2: Now go to your dropdown-menu folder Install the dependencies required in this project by typing the given command in the terminal.

cd dropdown-menu
npm install

Now create the components folder in src then go to the components folder and create two files Dropdown.jsx and style.css.

Folder Structure

folder_structure
Folder Structure

Dependencies

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example:

CSS
/* style.css */

.container {
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

.dropdown {
    padding: 20px;
    cursor: pointer;
}

.answer {
    font-weight: 500;
    font-size: 35px;
    margin-left: 10px;
}
JavaScript
// Dropdown.jsx

import "./style.css";

import React, { useState } from "react"

const Dropdown = () => {
    const [selectedValue, setSelectedValue] = useState("");

    const handleChange = (event) => {
        setSelectedValue(event.target.value);
    }
    console.log("value >>", selectedValue);
    return (
        <div className="container">
            <h3>select an Option from DropDown Menu</h3>

            <select value={selectedValue}  
            onChange={handleChange} className='dropdown'>
                <option value="">--Choose an option--</option>
                <option value="option1">Option 1</option>
                <option value="option2">Option 2</option>
                <option value="option3">Option 3</option>
            </select>

            {/* Displaying the selected value */}
            <p>Selected Value: <span className=" answer">
            {selectedValue.length === 0 ? "No option selected" : selectedValue}
            </span></p>
        </div>
    )
}

export default Dropdown;
JavaScript
// App.js

import React from "react"
import Dropdown from "./components/Dropdown"

const App = () => {


    return (
        <div>
            <Dropdown></Dropdown>

        </div>
    )
}

export default App


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:


Next Article
Article Tags :

Similar Reads