Reputation: 41
I use the map method on an array of objects to create a button:
arrayOfObjects.map(obj => (
<button value={obj} onClick={handleClick} key={obj._id}>
{obj.name}
</button>
where:
const handleClick = ({ target }) => {
const obj = target.value
onClick(obj) // this onClick is a prop from another React function component
}
How do I get the object itself ? With this, I get the following: The onClick method would set the state of my component but it is not what I'm looking for
Upvotes: 1
Views: 1221
Reputation: 5101
Value gets stored as a string, not an object.
You should instead do something like
arrayOfObjects.map(obj => (
<button onClick={()=>onClick(obj)} key={obj._id}>
{obj.name}
</button>
Upvotes: 0
Reputation: 514
You can wrap the handleClick function with the object:
const handleClick = (obj) => () => {
onClick(obj)
}
and with the buttons:
arrayOfObjects.map(obj => (
<button onClick={handleClick(obj)} key={obj._id}>
{obj.name}
</button>
Upvotes: 2
Reputation: 4684
Replace your code with this
arrayOfObjects.map(obj => (
<button :value=obj onClick="handleClick" :key=obj._id>
{{obj.name}}
</button>
Upvotes: 0