Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass id through on click react.js

Below is my partial code but my question is very simple, how can I get says data-id="1" to my function when user clicked on the li?

render(){
    return(
      <ul id="todo">
      {this.state.items.map((item,i) => 
        <li className='list-group-item' key={i} data-id={item.id}>{item.name}
        <button onClick={//how to pass item.id to my function?}>X</button>
        </li>
      )}
      </ul>
    ) 
  }
like image 327
Thian Kian Phin Avatar asked Oct 02 '16 15:10

Thian Kian Phin


People also ask

How do you get ID on button click in React?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do you pass id in a tag in react JS?

You can do this as follows : class Test extends React. Component { constructor(props){ super(props); this. state = { items: [ {item: "item", id: 1}, {item1: "item1", id: 2} ] } } handleClick(id, e){ alert(id); } render(){ return( <ul id="todo"> {this.

How do you pass a value on onClick React?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...

How get ID from option in select React?

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option. This is a bit of an anti-pattern for React.


1 Answers

Since you are already using ES6 - might be a little cleaner to use an arrow function here:

render(){
    return(
      <ul id="todo">
      {this.state.items.map((item,i) => 
        <li className='list-group-item' key={i} data-id={item.id}>{item.name}
        <button onClick={() => this.yourfunc(item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
}
like image 167
syllabix Avatar answered Oct 20 '22 20:10

syllabix