Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get component's id after clicking on it – react

I have array of objects in rides-context.js. In RidesList.js I map data from array to component and display it on screen.

const RidesList = (props) => {
  const rideCtx = useContext(RidesContext);

  const deleteHanlder = () => {
    rideCtx.onDelete(??)
  }
 
  return (
    <ul className={classes.container}>
      {rideCtx.ridesList.map((ride) => (
        <Ride hour={ride.hour} name={ride.name} key={ride.key} id={ride.id} onDelete={deleteHanlder}/>
      ))}
    </ul>
  );
};

Now I want to delete component after clicking on it. In order to do that I have to pass component’s id to function which is located in rides-context.js. How can I get id of element that I have clicked on?(onDelete is connected to onClick in another file)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you want here is to use a closure and pass the id of the ride to the deleteHandler in the place where this is available. To do so you can pass an anonymous function as the onDelete prop, which is gonna be called with the ride.id like below:

const RidesList = (props) => {
  const rideCtx = useContext(RidesContext);

  const deleteHanlder = (id) => {
    rideCtx.onDelete(id)
  }
 
  return (
    <ul className={classes.container}>
      {rideCtx.ridesList.map((ride) => (
        <Ride hour={ride.hour} name={ride.name} key={ride.key} id={ride.id} onDelete={() => deleteHandler(ride.id)}/>
      ))}
    </ul>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading