Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the id of a clicked element from rendered list

What is the best way to get an id from a clicked element of a list? I am trying to render a list of items and then display an item detail view for the clicked item.

e.g

render() {
  let list = data.map((obj) => {
               return <div key={obj[id]} id={obj[id]} onClick={this.handleClick}></div>         
             });
  return <div>{list}</div>;
}

How do I get the id of the clicked element for use in another component?

like image 683
devsr Avatar asked Jun 02 '17 09:06

devsr


2 Answers

You can get the id from the click event directly. No need to bind the variable to the event handler.

render() {
    let list = data.map((obj) => {
       return <div key={obj[id]} id={obj[id]} onClick={this.handleClick}></div>         
    }
    return <div>{list}</div>;
}

handleClick(e){
   console.log(e.target.id);
}

A slightly modified working example:

class MyApp extends React.Component {
  handleClick(e){
    console.log(e.target.id);
  }
  
  render() {
    let data = [0,1,2,3,4];
    let list = data.map((obj, id) => {
      return <div key={obj[id]} id={"id-" + id} onClick={this.handleClick}>{obj}</div>         
    });
    return <div>{list}</div>
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>
like image 115
Chris Avatar answered Oct 17 '22 23:10

Chris


Pass the id in onClick method for each element:

render() {
    let list = data.map((obj) => {
       return <div key={obj.id} id={obj.id} onClick={() => this.handleClick(obj.id)}></div>         
    }
    return <div>{list}</div>;
}

handleClick(id){
   console.log(id);
}
like image 11
Mayank Shukla Avatar answered Oct 17 '22 21:10

Mayank Shukla