NavLink on logo image does not work in React

·

1 min read

In this blog I am going to tell how to fix the problem of not getting a working link when a image is inside in NavLink of react router . For example I was trying to do add this function as an onClick event in every NavLink

<NavLink  onClick={(e)=>{IfSamePathThenScrollToTop(e)}} to="/" className=" navbar-brand ">
                <img src={causalLogo} className="causalLogo img-fluid" alt="CausalFunnel Logo"/>
              </NavLink>
function IfSamePathThenScrollToTop(e)
  { 
    console.log(e.target);
    if (window.location.pathname === e.target.pathname)
    {
       window.scrollTo(0, 0);
    }

    return null;
  }

export default IfSamePathThenScrollToTop

the problem which I was getting was that the image element was being printed as the target in the console instead of an anchor tag which means my function was trying to access pathname property of an img element which didn't even exist .

Solution

I changed target to currentTarget

target vs currentTarget

target means the element which fired the eventListener. currentTarget means the element to which the eventListener is attached. Hence I was able to get the anchor element printed in the console.