Value Attributes in Select in React
Now let's say that in our option tags we have value attributes:
function App() {
return <div>
<select>
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
</div>;
}
In this case, due to the presence of the value attributes, their values will be included in the state, and not the texts of the option tags. You can verify this by displaying the selection result in a paragraph:
function App() {
const [value, setValue] = useState('');
return <div>
<select value={value} onChange={(event) => setValue(event.target.value)}>
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<p>
your choice: {value}
</p>
</div>;
}
It can be convenient to separate the text option and its value: we can change the text of the tag as we like, while in our script the result of the selection will be processed by the value of the attribute value, which will remain unchanged.
See example:
function App() {
const [value, setValue] = useState('');
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<p>
{value === '1' && 'you chose the first item'}
{value === '2' && 'you chose the second item'}
{value === '3' && 'you chose the third item'}
</p>
</div>;
}
Now, if we change the texts of the option tags, the script will not be disrupted - after all, it is tied to the value of the value attribute.
Using a drop-down list, ask the user to select which age group they belong to: from 0 to 12 years old, from 13 to 17, from 18 to 25, or older than 25 years old.