Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button inside anchor tag

Tags:

html

reactjs

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?

like image 260
jaehyuk kim Avatar asked Sep 18 '25 10:09

jaehyuk kim


1 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>
  )
like image 114
Dhruv Roy Talukdar Avatar answered Sep 20 '25 02:09

Dhruv Roy Talukdar