I am not sure if this is even possible but I have a table that has an onClick event on each row that directs the user to another page. I need to add a button inside each row to handle a separate event. But everytime I click the button the action to redirect to a new page is fired. Is it possible to have a click event inside another?
example:
items.map((item) => {
return(
<tr onClick={onClick(item.value)}>
<td>{item.Name}</td>
<td>
{visitCreated}
<span>
<button
type="button"
onClick={handlePreview(item.referenceID)}>
Preview
</button>
</span>
</td>
<td>{item.Encounters}</td>
</tr>
})
Anytime I click the both events are triggered. How can I isolate them?
CodePudding user response:
The fastest way would be to wrap the onClick handlers in an arrow function:
onClick={()=>onClick(item.value)}
onClick={()=>handlePreview(item.referenceID)}
items.map((item) => {
return(
<tr onClick={()=>onClick(item.value)}>
<td>{item.Name}</td>
<td>
{visitCreated}
<span>
<button
type="button"
onClick={()=>handlePreview(item.referenceID)}>
Preview
</button>
</span>
</td>
<td>{item.Encounters}</td>
</tr>
})
CodePudding user response:
Could do something like this:
document.querySelector("button").addEventListener("click", function(e) {
console.log("Clicked the button");
e.stopPropagation();
e.preventDefault();
});
const rowClick = (event) => {
console.log("Clicked the row");
};
tr {
display: flex;
}
td {
border: 3px solid;
}
<table>
<tr onclick={rowClick()}>
<td>{item.Name}</td>
<td>
{visitCreated}
<span>
<button
type="button" >
Preview
</button>
</span>
</td>
<td>{item.Encounters}</td>
</tr>
</table>
CodePudding user response:
You can add an id on the button, and check if the target has this id to prevent one or the other event. Something like
function onClick(event) {
if (event.target.id !== 'button_id') {
// do something
}
event.stopPropagation()
}
function handlePreview(event) {
if (event.target.id === 'button_id') {
// do something else
}
event.stopPropagation()
}
...
items.map((item) => {
return(
<tr onClick={onClick(item.value)}>
<td>{item.Name}</td>
<td>
{visitCreated}
<span>
<button
type="button"
id="button_id"
onClick={handlePreview(item.referenceID)}>
Preview
</button>
</span>
</td>
<td>{item.Encounters}</td>
</tr>
})