In this quick post we will be covering how to set the “selected” option on a select element with React and JSX so you can solve this issue quickly and without having to look any further!
As with all my Quick Fix Series of posts, you will first find the problem described and then the solution just below.
Let’s get stuck in!
The problem - Setting the “selected” option on a select element with React and JSX
When using React and JSX, from time to time you will encounter a scenario where you need to use a select
element.
In standard HTML you could set the selected
element by marking it on the option as “selected”.
For example:
<select name="example">
<option value="1" selected>1</option>
<option value="2">2</option>
</select>
The issue here comes from how in React and JSX we usually control our components and you don’t really want to have to perform a boolean check on each and every option element to mark whether it has been selected or not.
The Solution - setting “selected” on a select element with React and JSX
React and JSX actually handle this for us straight out of the box so we don’t need to worry about having to check each option to see whether it needs to be selected or not.
All we need to do is to define a value
prop on the parent select
element and then pass in whatever value has been selected.
Here is an example of how we can do that:
<select name="example" value={selectedElement} onChange={handleChange}>
<option value="1">1</option>
<option value="2">2</option>
</select>
You can read more about this here in the React docs.
Lastly, it is also worth noting that this also works with multiple options as well.
This means that if you have set the multiple
attribute/prop in the select element and you can select multiple option elements, to be able to control that with React and JSX all you need to do is provide an array to the value
prop/attribute of the parent select elements in the same way as above.
export default function Example() {
const [selectedElements, setSelectedElements] = useState([])
return (
<select
name="example"
multiple
value={selectedElements}
onChange={handleChange}
>
<option value="1">1</option>
<option value="2">2</option>
</select>
)
}
Summary
There we have the quick fix to how to set the “selected” option on a select element with React and JSX, if you want more like this be sure to check out some of my other posts!