How to create a drop-down in React.js?

Member

by deron , in category: Javascript , 3 months ago

How to create a drop-down in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months ago

@deron 

To create a drop-down in React.js, you can follow these steps:

  1. Import the necessary components from the React library:
1
import React, { useState } from 'react';


  1. Create a functional component that holds the drop-down:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function Dropdown() {
  const [selectedOption, setSelectedOption] = useState('');
  
  const handleOptionChange = (e) => {
    setSelectedOption(e.target.value);
  }
  
  return (
    <select value={selectedOption} onChange={handleOptionChange}>
      <option value="">Select an option</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
  );
}


  1. In the above code, we use the useState hook to create a state variable selectedOption, which stores the currently selected option in the drop-down. We also use the setSelectedOption function to update the selected option.
  2. Within the return statement, we create a element is set to the selectedOption state variable, which controls the selected value. The onChange event is handled by the handleOptionChange function, which updates the selectedOption state variable upon selecting a different value.
  3. Lastly, you can use this Dropdown component within your parent component as follows:
1
2
3
4
5
6
7
function App() {
  return (
    <div>
      <Dropdown />
    </div>
  );
}


This will render the drop-down with the default option "Select an option" and three additional options: "Option 1", "Option 2", and "Option 3". The selectedOption state variable will store the currently selected option, and it will update whenever a different option is selected.