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?
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>
})
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 class="previewButton" type="button" > Preview </button> </span> </td> <td>{item.Encounters}</td> </tr> </table>
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>
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.