Home > OS >  How to get component's id after clicking on it - react
How to get component's id after clicking on it - react

Time:12-23

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)

CodePudding user response:

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