How to use HTML <select> tag in ReactJS ?
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:
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.
Step to Run Application: To run the application, execute the below command from the root directory of the project:
Output: Your web application will be live on “http://localhost:3000”. Now click on the dropdown to select any value.