3

I have a component entirely linked in a <Link> tag but I have inside an icon that I want clickable without activating the link. Is there a way to escape the icon?

<Link to={`/post/${id}`} className='flex flex-row px-3 py-2'>
  <div>Some content</div>
  <i onClick={anAction}>An Icon</i>
  <div>Some content</div>
</Link>
3

3 Answers 3

3

You should use e.preventDefault()

<Link to={`/post/${id}`} className='flex flex-row px-3 py-2'>
  <div>Some content</div>
  <i onClick={(e) => {e.preventDefault(); //rest of your function}}>An Icon</i>
  <div>Some content</div>
</Link>
3

This is an example of a component that stops the default behavior, but I highly discourage doing this kind of stuff overall. I would rather wrap only what can be clicked in the <Link> if possible (in your use case it’s fine) .

import { Link } from "react-router-dom";

const Test = () => {
  const handleOnClick = (e) => {
    e.preventDefault();
    console.log("hello");
    // ...rest
  };

  return (
    <Link to={"/another-page"}>
      Some text
      <i onClick={handleOnClick}>Hello</i>
    </Link>
  );
};

export default Test;
2

Generally you should avoid rendering interactive elements inside other interactive elements. If you just want the icon alone to be clickable and not activate the link, but anywhere else within the link should activate it, then prevent the click event in the icon from propagating and allowing the default link action to occur.

Example:

const anAction = e => {
  e.preventDefault();
  e.stopPropagation();

  ...
};

...

<Link to={`/post/${id}`} className='flex flex-row px-3 py-2'>
  <div>Some content</div>
  <i onClick={anAction}>An Icon</i>
  <div>Some content</div>
</Link>

Not the answer you're looking for? Browse other questions tagged or ask your own question.