Shruthi R
Shruthi R

Reputation: 1923

ReactJS - How to render single object from an array using id?

In react app, I am trying to get single row from an array using id but it doesn't work.

const result = [
 {id: 0, important: false, name: "Shruthi R", phone: "9834233433", email: "[email protected]", work: "NicheSoft", city: "Mysore"},
 {id: 1, important: false, name: "Shivay", phone: "9442233166", email: "[email protected]", work: "MicroSoft", city: "Mumbai"},
 {id: 2, important: false, name: "Yash Sindhya", phone: "7455454354", email: "[email protected]", work: "AirVoice", city: "Pune"},
 {id: 3, important: false, name: "Rajat", phone: "8456546555", email: "[email protected]", work: "Airtel", city: "Delhi"},
 {id: 5, important: false, name: "Surya S", phone: "9956546546", email: "[email protected]", work: "Vodafone", city: "Chennai"},
 {id: 6, important: false, name: "Paridhi", phone: "8856544422", email: "[email protected]", work: "MicroTech", city: "Lucknow"},
];

My onEditClick function is as shown below, here I want single(matching) row from an result using id

onEditClick = (event) => {
  console.log(event.target.id);
}

Upvotes: 0

Views: 985

Answers (1)

Ro Milton
Ro Milton

Reputation: 2526

Provided event.target.id contains the relevant ID, you can use array method find():

onEditClick = (event) => {
  const clickedResult = result.find(({id})=>id===parseInt(event.target.id));
  console.log('clickedResult', clickedResult);
}

Upvotes: 2

Related Questions