Open In App

How to use HTML <select> tag in ReactJS ?

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

HTML <select> tag in react is a common web development component used for dynamic form input or as a select menu. It provides multiple selection options in the form of a dropdown menu. It enables the web page to render a select box with the options. The <select>  tag is used as an outer element and the <option> element is nested within the <select> tag for defining options in a list.

How to use Select tag in React ?

To use the select tag in React we will use HTML Select and create an array for the drop-down options. Use the HTML Select tag and inside iterate the array elements using array map to render the items as options. On the <select> tag, we will use the “onChange” property which will hold a reference to the “onOptionChangeHandler” function. This function will get triggered whenever we change the value of the dropdown.

Steps to create the application

Step 1: Create a React.js application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move into that directory using the following command:

cd foldername

Project Structure

Screenshot-from-2023-10-06-12-56-14

Example: In this example we will create a dropdown selection input with some options present in the given options array.

CSS
/* App.css */
.App {
    text-align: center;
}

.geeks {
    color: green;
}
JavaScript
// App.js

import React, { useState } from "react";
import "./App.css";

const App = () => {
    const [data, setData] = useState(undefined);

    const options = [
        "HTML",
        "CSS",
        "JavaScript",
        "React",
        "Redux",
    ];
    const onOptionChangeHandler = (event) => {
        setData(event.target.value);
        console.log(
            "User Selected Value - ",
            event.target.value
        );
    };
    return (
        <center>
            <h1 className="geeks"> GeeksforGeeks</h1>
            <h3>HTML select tag in React js</h3>

            <select onChange={onOptionChangeHandler}>
                <option>Please choose one option</option>
                {options.map((option, index) => {
                    return (
                        <option key={index}>
                            {option}
                        </option>
                    );
                })}
            </select>
            <h3>You selected: {data} </h3>
        </center>
    );
};

export default App;

Step to Run Application: To run the application, execute the below command from the root directory of the project:

npm start

Output: Your web application will be live on “http://localhost:3000”. Now click on the dropdown to select any value. 

Peek-2023-10-06-12-48



Next Article

Similar Reads