Sometimes, we want to add select option with object as the value attribute value with React.
In this article, we’ll look at how to add select option with object as the value attribute value with React.
How to add select option with object as the value attribute value with React?
To add select option with object as the value attribute value with React, we can set the value
attribute to the index and then select the object from the index from the options array.
For instance, we write:
import React, { useState } from "react";
const options = [{ name: "apple" }, { name: "orange" }, { name: "grape" }];
export default function App() {
const [option, setOption] = useState({});
console.log(option);
const handleChange = (e) => {
setOption(options[+e.target.value]);
};
return (
<select onChange={handleChange}>
{options.map((option, index) => (
<option key={index} value={index}>
{option.name}
</option>
))}
</select>
);
}
We have an array of options
that we render as options in the select drop down.
To do the rendering, we call options.map
with a callback that returns the option elements.
We set the value
attribute value to index
so we can select the object from the list once we selected an option.
Next, we define the handleChange
function that calls setOption
with options[+e.target.value]
to set option
to the selected object from options
.
e.target.value
has the value
attribute value of the option element selected.
Therefore, from the console log, we see the object that corresponds to the options we selected from the drop down.
Conclusion
To add select option with object as the value attribute value with React, we can set the value
attribute to the index and then select the object from the index from the options array.