'What is the alternative for selected default in React?

In the HTML, I got something like this for select.

What it's doing is the default value showing for the select dropdown is Select year but it cannot be selected.

<select>
    <option disabled hidden selected>
        Select Year
    </option>
    <option value="2021">2021</option>
</select>

But when I implement it in React.

It giving me this error

Use the defaultValue or value props on instead of setting selected on .

But when I use default value or value the SELECT YEAR option is not there anymore.



Solution 1:[1]

All you need is to remove both selected and disabled attributes from first <option>:

<select>
  <option hidden>Select Year</option>
  <option value="2021">2021</option>
</select>

Here's why:

<select> is shorthand for <select defaultValue={undefined}>, which makes the first <option> with a value of undefined get selected. In your case, that's the first <option>, since it doesn't have a set value, which is equivalent to having a value set to undefined.

Probably the most important bit is removing disabled. Remember this is JSX, not HTML. JSX is used by React to create valid HTML. If you specify disabled attribute, React won't allow that <option> to be selected, regardless of method.
But you want that <option> selected by default, so it doesn't make sense to disable it.
You only want the user not to be able to select it, which is exactly what the hidden attribute does.

Working demo.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1