Set a Placeholder on a Select tag in React-Code Examples

Radu TM

Set a Placeholder on a Select tag in React

JavaScript by Radu TM β€’ June 16, 2022

import { useState } from 'react';

const App = () => {
  const options = [
    { value: '', text: '-- Select One Option --', disabled: true },
    { value: 'orange', text: 'Orange 🍊' },
    { value: 'grape', text: 'Grape πŸ‡' },
    { value: 'watermelon', text: 'Watermelon πŸ‰' },
    { value: 'banana', text: 'Banana 🍌' },
    { value: 'strawberry', text: 'Strawberry πŸ“' },
  ];

  // The initial value of the select is the first option
  const [selected, setSelected] = useState('');

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

  return (
    <div>
      <select value={selected} onChange={handleChange}>
        {options.map(option => (
          <option
            disabled={option.disabled}
            key={option.value}
            value={option.value}
          >
            {option.text}
          </option>
        ))}
      </select>
    </div>
  );
};

export default App;

0

26.387

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories