Embedded button in link are, how to stop onClick chaining

I have code similar to below example. I am trying make a grid cell that is clickable sending the user to a url, except when clicking on an embedded image button, I just want that onClick firing, not the other one, is it possible to do something like that? I’ve tried adding a call to stopPropagation, however it still chain to the underlying link after handling the first onClick.

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>

>Solution :

You can make use of the e.preventDefault() function in your handleSaveClick function. When the embedded image button is clicked, the handleSaveClick function will be executed, and the e.preventDefault() should prevent the default behaviour of the link, ensuring that it doesn’t navigate to the URL.

const handleSaveClick = async (e, activity, index) => {
  e.preventDefault(); // Prevent the default behavior (following the link)
  e.stopPropagation(); // Stop the event from bubbling up

  // Your button click logic here
  // ...
}

Also You should consider replacing the anchor tag for the clickable area or the button with another suitable element.

Leave a Reply