Search code examples
reactjsnext.jsnext-routernext-link

How to navigate correctly in nextjs


idk it's pretty simple or what but having difficulty understanding it. here is one parent div wrapped with nextjs Link tag(which navigates me to /playing route) and in this div i have one more tag which can navigate me to login page. here is the problem when click on login it navigates first /playing page and then it navigates me to the /login what is the correct way to resolve it. i want to navigate to the /playing by clicking on whole div and

  <Link href="/playing">
        <div className="px-20 w-full">
          <h1 onClick={() => router.push(`/login`)} className="hover:underline">
            Login
          </h1>
        </div>
      </Link>

Solution

  • This problem is caused by propagation or event bubbling. read event action in javascript for more information. But in your section you need to avoid click-through propagation. try this :

      <Link href="/playing">
            <div className="px-20 w-full">
              <h1 onClick={(event) => {
               event.stopPropagation();
               router.push(`/login`);
             }} 
             className="hover:underline">
                Login
              </h1>
            </div>
      </Link>
    
    

    if this sample not working. search about event bubbling