I’m experiencing a weird response by my onClick event handling.
I have a list of user boxes, which on click, I’m attempting to navigate the client to that specific user’s page ( as if – navigate("/farmershop/" + e.target.id) )
I am debugging by console.logg my e.target.id, I only get the id (which I attempt to retrieve) printed when I click on certain areas in the user box. In case I don’t press that specific part in the box (on the image), I get an empty string.
These are my functions responsible for stated task:
const handle_clicked_farmer = (e) => {
console.log(e.target.id);
navigate("/farmershop/" + e.target.id);
}
const createTopFarmers = () => {
return top_n_farmers.map((farmer) => ( // on click take to farmer's page.
<Stack sx={{marginTop: "3%", background: "green", marginLeft:"5%", width: "400px", borderRadius:"5px", boxShadow: "2px 3px 8px black"}}>
<Box sx={{marginLeft:"2%", cursor: "pointer" }} onClick={handle_clicked_farmer} id={farmer.id}>
<Typography sx={{fontFamily: "Amatic SC", letterSpacing: "2px", fontSize: "50px", fontWeight: 700}}>{farmer.firstname}</Typography>
<Typography sx={{fontFamily: "Amatic SC", letterSpacing: "2px", fontSize: "50px", fontWeight: 700, marginTop: "-5%"}}>{farmer.lastname}</Typography>
<img src={farmer.img} style={{width: "100px", borderRadius: "300px", border: "2px solid black"}}/>
<Typography sx={{fontFamily: "Amatic SC", letterSpacing: "2px", fontSize: "20px", fontWeight: 700, marginTop: "-5%"}}>location: {farmer.location}</Typography>
</Box>
<Box>
{farmer.likes} likes
</Box>
<Box sx={{backgroundColor: "green"}}>
<Typography sx={{fontFamily: "Amatic SC", fontSize: "25px"}}>{farmer.about}</Typography>
</Box>
</Stack>
));
};
any ideas what might be the issue?
regards!
>Solution :
First!
e.target is a DOM element, so e.target.id is the ID of the DOM element. Having a prop id={id} in a JSX component DO NOT guarantee you that the component will actually render a DOM element with the provided id
Second!
Speaking of DOM element, the id must be uniq on the page
So maybe for you, best would be to have something like:
const handle_clicked_farmer = id => () => {
navigate("/farmershop/" + id);
}
const createTopFarmers = () => {
return top_n_farmers.map((farmer) => ( // on click take to farmer's page.
...
<Box onClick={handle_clicked_farmer(farmer.id)}>
...