We can set the default value of a React select element by using the useState
hook.
The default value can be set as the default value of the hook. Then we can set it as the value of the value
prop of the select
element.
For instance, we can write:
import React, { useState } from "react";
const fruits = ["orange", "apple", "grape"];
export default function App() {
const [fruit, setFruit] = useState("apple");
return (
<div className="App">
<select
value={fruit}
onChange={e => setFruit(fruits[e.target.selectedIndex])}
>
{fruits.map(f => (
<option value={f}>{f}</option>
))}
</select>
<p>{fruit}</p>
</div>
);
}
We set the value
prop to fruit
so that we set the initial value of it.
We map the fruits
entries to the option
elements.
Then we add an onChange
handler to call setFruit
as we change selection.
We get the selected value from the fruits
array by writing:
fruits[e.target.selectedIndex]
so that we get the string given the index of the selected option.
Then we display the selected value so that we can see what we selected below the select element.
Since we set the initial value of the fruit
state to 'apple'
, that’s what we display when we load the select element, which means that it’s the default value.
Now we can have default values for our React select elements.