You can set multiple default options in a <select multiple>
HTML element using React by providing an array of values to the defaultValue
attribute on the <select>
tag.
For example, let's consider the following React component with a multi-select HTML element:
function MultiSelect() { return ( <select multiple defaultValue={['rock', 'hip-hop']}> <option value="rock">Rock</option> <option value="pop">Pop</option> <option value="country">Country</option> <option value="hip-hop">Hip-Hop</option> </select> ); }
In this example, the options with the values "rock
" and "hip-hop
" will be selected by default, resulting in the following output:
As you can see in the example above, the values in the array that match the corresponding <option value>
will be selected by default.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.