TechSelfLearner
TechSelfLearner

Reputation: 397

getting element id in React.js JSX rendering using .map() method

I am working on app using react,

const getButtonId=(num)=>{
   let click_detect=document.getElementById('div_'+num)
   console.log(click_detect)
}

this.state.users.map(i=>{
   return(
    <button id={'div_'+i.id} onClick={(i.id)=>this.getButtonId(i.id)}>
      Click Me
    </button>
  )
})

So every time I clicked on the button, I kept getting null. Why is that? If I want all buttons to have different id, What should I do here?

Upvotes: 0

Views: 615

Answers (1)

Abdullah Khan
Abdullah Khan

Reputation: 1473

Try this:


const getButtonId = (id) => console.log("Button ID:", id);

this.state.users.map((user, index) => (
   <button key={index} onClick={() => this.getButtonId(user.id)}>
      Click Me
   </button>
))

Upvotes: 1

Related Questions