How to make links work with card-img-overlay React

388 Views Asked by At

I'm having an issue on my project. I created a card-img-overlay to display icons over an image. If you click on the entire image you are redirected to a post. I would like to make the like and share icons clickable.

My project is in Reactjs. I am displaying images and videos from Reddit API.

Thank you for your help.

  id,
  slugTitle,
  title,
  url_overridden_by_dest,
  author,
  preview,
}) => {
  const [isVideo, setIsVideo] = useState(false);
  useEffect(() => {
    if (preview) setIsVideo(preview.split('.').pop() === 'mp4');
  }, [preview]);
  const history = useHistory();

  const goToPage = () => {
    history.push(`/Post/${id}/${slugTitle}`);
  };

  return (
    <Card
      inverse
      onClick={goToPage}
      style={{
        cursor: 'pointer',
      }}
    >
      {isVideo && (
        <video autoPlay="false" loop width="100%" src={preview}>
          <track default kind="captions" />
        </video>
      )}
      {!isVideo && (
        <CardImg top width="100%" src={url_overridden_by_dest} alt={title} />
      )}
      <CardImgOverlay className="hideinfos">
        <CardText className="w-100 d-flex justify-content-between">
          <div>
            <VscAccount className="mr-2" size={20} />
            {author}
          </div>
          <div>
            <LikeButtonhp
              className="mr-2 card-link"
              size={20}
              style={{
                position: 'relative',
              }}
            />
            <BiShareAlt size={20} />
          </div>
        </CardText>
      </CardImgOverlay>
    </Card>
  );
};
2

There are 2 best solutions below

1
On

You'll need to put onClick handlers on your LikeButtonhp and BiShareAlt components, and use event.stopPropagation() to stop the event from bubbling up to the <Card />:

<BiShareAlt
    size={20}
    onClick={event => {
        event.stopPropagation();
        // Do stuff for share click
    }}
/>

You may need to alter the BiShareAlt and LikeButtonhp components to support an onClick prop also, for example if they render a <button> element it may look like this:

const BiShareAlt = ({ onClick }) => (
    <button onClick={onClick}>
        Share
    </button>
);

export default BiShareAlt;
0
On

In my onClick, I added an e.stopPropagation(); and it solves my problem. Now I can click on the heart icon and it works. It stops the onClick set up on my image (parent).

function LikeButtonhp() {
  const [liked, setLiked] = useState(false);
  return (
    <Button
      outline
      color="link"
      className="likebutton"
      onClick={(e) => {
        e.stopPropagation();
        setLiked(!liked);
      }}
      style={{ color: 'white' }}
    >
      {liked ? <BsHeartFill size={20} /> : <BsHeart size={20} />}
    </Button>
  );
}