2

I want to have a default option in select saying "Select your option". But I want in to be disabled, which means that user should not be able to select it once he choose any value.

Here is an example:

function Select() {
    const [option, setOption] = useState();

    function handleOnChange(event) {
        setOption(event.target.value);
    }

    return (
        <select value={option} onChange={handleOnChange}>
            <option disabled>Select your option</option>
            {OPTIONS.map(value => (
                <option key={value} value={value}>{value}</option>
            ))}
        </select>
    );
}

But if I'm adding a disabled prop to option it selects the first option which is not disabled. What should be adjusted to make it work?

Thanks in advance

coder
  • 23
  • 4
  • Does this answer your question? [How do I make a placeholder for a 'select' box?](https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box) – gunwin Jul 26 '22 at 09:44

1 Answers1

1

what you need to do is to provide a default value to your useState and a value for your default option, so it gets selected. Like this:

function Select() {
    const [option, setOption] = useState('');

    function handleOnChange(event) {
        setOption(event.target.value);
    }

    return (
        <select value={option} onChange={handleOnChange}>
            <option value='' disabled>Select your option</option>
            {OPTIONS.map(value => (
                <option key={value} value={value}>{value}</option>
            ))}
        </select>
    );
}
Artem Matiushenko
  • 814
  • 10
  • 14