I have an array of objects in rides-context.js. In RidesList.js I map the data of the array and pass it to the component in order to display it on screen.
const RidesList = (props) => {
const rideCtx = useContext(RidesContext);
const deleteHandler= () => {
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={deleteHandler}/>
))}
</ul>
);
};
Now I want to delete a component after clicking on it. In order to do so, I have to pass the component's id to the function which is located in rides-context.js. How can I get the id of the element that's been clicked?(onDelete is connected to onClick in another file)
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>
);
};