nalanart
nalanart

Reputation: 41

How can I get the object from a button's value?

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

Answers (3)

Tiago Coelho
Tiago Coelho

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

Cody S
Cody S

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

Amaarockz
Amaarockz

Reputation: 4684

Replace your code with this

arrayOfObjects.map(obj => ( 
  <button :value=obj onClick="handleClick" :key=obj._id>
    {{obj.name}}
  </button>

Upvotes: 0

Related Questions