devsr
devsr

Reputation: 103

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?

Upvotes: 10

Views: 15123

Answers (2)

Chris
Chris

Reputation: 59491

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>

Upvotes: 14

Mayank Shukla
Mayank Shukla

Reputation: 104369

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

Upvotes: 11

Related Questions