button inside anchor tag

Viewed 96

I am trying create a like button inside a post. ex) Shopping mall post where you click the post then goes to post detail page, but when you click button, you dont move page but mark only the like button.

import {isLoggedIn} from "recoil/AtomUser" // recoil is an alternative to redux
import {Link, useNavigate} from "react-router-dom"

const FashionItem = ({ItemNo}) => {
  const navigate = useNavigate();
  const [isLike, setIsLike] = useState(false);
  const handleLike = ()=>{
    if (!isLoggedIn){
        alert("please login");
        navigate("/login");
    }
  };
  return (
    <Link to=`/itemDetail/${ItemNo}`>
      <img />
      <button onClick={handleLike}>Like Image (heart)</button>
    </Link>
  )
};

The problem is I want to separate the case where user clicks like button and where user wants to see the detail of the post.

I found that nesting button inside anchor tag is not valid. How should i approach solving this issue?

I just found a way to possibly solve this: placing input tag inside anchor tag seems to work! Seems like input tag ignores anchor tag that are nested around it. Do you think this is the solution?

3 Answers

This solution worked for me

  function handleLike(e) {
    // Add these two lines
    e.stopPropagation();
    e.preventDefault();
    // Other logic of button click below
    if (!isLoggedIn){
        alert("please login");
        navigate("/login");
    }
  }
  
  return (
    <Link to=`/itemDetail/${ItemNo}`>
     <img />
     <button onClick={handleLike}>Like Image (heart)</button>
    </Link>
  )

A simple solution would be to wrap the link in a and give it a position: relative, then take the button out of the link tag and give it a position absolute and position it wherever you want. You can also prevent the click event from bubbling to the parent anchor tag by using e.preventDefault(), but you'll still have the button inside a link situation which is not a valid HTML and will cause accessibility issues.

<div style={{position: "relative"}}>
  <Link to=`/itemDetail/${ItemNo}`>
      <img />
      <button onClick={(e) => e.preventDefault()}>Like Image (heart)</button>
  </Link>
</div>
return (
  <div>
    <Link to=`/itemDetail/${ItemNo}`>
      <img />
    </Link>
    <button onClick={handleLike}>Like Image (heart)</button>
  </div>
)

(or)

return (
  <>
    <Link to=`/itemDetail/${ItemNo}`>
      <img />
    </Link>
    <button onClick={handleLike}>Like Image (heart)</button>
  </>
)
Related