Home > Back-end >  Add a disabled default option to select
Add a disabled default option to select

Time:07-26

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

CodePudding user response:

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>
    );
}
  • Related