How to usethe native ‘select’ element in ReactJS

In this approach we are using the built-in HTML <select> element provided by the browser. We will use state to manage the selected option.

Example: This example uses native <select> element to set the option of a select in React.

JavaScript
import React, { useState } from 'react';

function App() {
    const [selectedOption, setSelectedOption] = useState('');

    const handleChange = (event) => {
        setSelectedOption(event.target.value);
    };

    return (
        <div>
            <h3>Welcome to w3wiki</h3>
            <select
                value={selectedOption}
                onChange={handleChange}
                style={{
                    padding: '10px',
                    fontSize: '14px',
                    borderRadius: '5px',
                    border: '1px solid #ccc',
                    width: '150px'
                }}>

                <option value="">Select State</option>
                <option value="Maharashtra">Maharashtra</option>
                <option value="Bihar">Bihar</option>
                <option value="Goa">Goa</option>
                <option value="Gujrat">Gujrat</option>

            </select>
            <p>Selected option: {selectedOption}</p>
        </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:

Using the native element

How to Set Selected Option of a Select in React?

In the React setting the selected option of a Select can be achieved using different approaches including using the native HTML <select> element and using third-party select components like react-select.

We will discuss two approaches to Setting selected options of a select in React:

Table of Content

  • Using the native ‘select’ element
  • Using react-select component

Prerequisites:

Similar Reads

Steps to Setup ReactJS Application

Step 1: Create a reactJS application by using this command...

Approach 1: Using the native ‘select’ element

In this approach we are using the built-in HTML elements....

Contact Us