Home > Net >  How to keep current tabIndex when navigating between NextJS pages
How to keep current tabIndex when navigating between NextJS pages

Time:10-14

How to properly save current tabIndex when navigating between pages?

(In ideas to make a function that will save the current index in the sessionStorage and retrieve it when the page is mounted)

Example:

enter image description here

enter image description here

CodePudding user response:

a Simple solution based on the useRouter hook:

import Link from "next/link";
import { useRouter } from "next/router";


export const MyNav = () => {

  const router = useRouter();

  return (
    <ul>
      <li className={router.pathname == "/" ? "active" : ""}>
        <Link href="/">API</Link>
      </li>
      <li className={router.pathname == "/users" ? "active" : ""}>
        <Link href="/users">Users</Link>
      </li>
    </ul>
  );
};

CodePudding user response:

You can use withRouter() library to figure out current URL and match it with the page URL and then add a different class with border or background-color to differentiate between them


You can also go with a much easier method and use :active and :visited selectors of CSS with the nav-item class or element.

  • Related