Skip to content
Related Articles

Related Articles

How to use HTML <select> tag in ReactJS ?

Improve Article
Save Article
  • Last Updated : 24 Aug, 2022
Improve Article
Save Article

HTML <select> tag is used to create a drop down list with multiple options. The <select>  tag is used as outer element and the <option> element is nested within <select> tag for defining options in a list.

Approach: To achieve this functionality, we will use “App.js” file and component which will be available by default in the project structure. In our “App.js” component, we will write the main logic. We will use HTML <select> tag and <option> tag. A constant array will be created which will have all the options. Under <select> tag we will iterate “options” array to display drop-down options. On <select> tag, we will use “onChange” property which will hold reference of “onOptionChangeHandler” function. This function will get triggered whenever we will change the value of dropdown.

Setting up React.js app:

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: The project structure will look like this:

 

Example: Let’s understand the implementation through the example:

App.js: In this file, we have the App component which is responsible for rendering JSX code. We will have a constant array named “options”, a change handler function named “onOptionChangeHandler” and JSX code enclosed in the return method.

Javascript




import React from "react";
  
const App = () => {
    const options = ['One', 'Two', 'Three', 'Four', 'Five'];
    const onOptionChangeHandler = (event) => {
        console.log("User Selected Value - ", event.target.value)
    }
    return (
        <>
            <center>
                <h1>Welcome to Geeks for Geeks</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>
            </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. 

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!