Thian Kian Phin Thian Kian Phin - 2 months ago 8
React JSX Question

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>
)
}

Answer

You can use bind() to do this.

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={yourfunc.bind(this, item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
  }

Your function will receive item.id as the first parameter

Comments