Getting the id of the clicked item from the displayed list

What is the best way to get the ID from a clicked list item? I am trying to display a list of items and then display a detailed item view for the clicked item.

eg

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 a clicked element for use in another component?

+3


source to share


2 answers


You can get directly id

from the event click

. There is no need to bind a variable to an 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);
}

      




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>
      

Run codeHide result


0


source


Pass the id in onClick

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

      

+3


source







All Articles