Embedded button in link, how to stop the chain effect of onClick link
P粉553428780
2023-08-17 21:31:04
<p>I have code similar to the example below. I'm trying to create a clickable grid cell that sends the user to a URL, but when the embedded image button is clicked I only want the onClick event to fire and no other events, is it possible to do this? I tried adding a call to stopPropagation, but after the first onClick is handled, it still links to the underlying link. </p>
<pre class="brush:php;toolbar:false;">const handleSaveClick = async (e, activity, index) => {
e.stopPropagation();
...
}
<Grid item>
<a className={clsx(classes.link)}
href={payload.shareableUrl}
onClick={() => handleLinkClick(payload.url, index)}
>
<Tooltip title={payload.title}>
<Typography className={clsx(classes.copy)}>
{payload.title}
</Typography>
</Tooltip>
<Button
className={clsx(classes.savedButton)}
onClick={(e) => handleSaveClick(e, payload, index)}
>
<img
className={clsx(classes.savedIcon)}
src={payload.isSaved ? saved : notSaved}
/>
</Button>
</a>
</Grid></pre>
In the handleSaveClick function, you can use the e.preventDefault() function. When the embed image button is clicked, the handleSaveClick function will be executed, e.preventDefault() should prevent the default behavior of the link, ensuring that it does not navigate to the URL.
Additionally, you should consider replacing the anchor tag of a clickable area or button with another suitable element.