preston
preston

Reputation: 13

NextJS React Tailwind CSS Navbar Active Styling

It's been a while since I've fiddled with React and just started learning Next.Js. I'm curious how I would change the background of my Navbar in Tailwind CSS based on the current boolean value "current" true/false on which page the user is on with Next Router.

It seems pretty simple, but it's gotten a little complicated for me to understand. The code is originally from one of the Tailwind CSS examples and there's an array of links with href and the current value with true/false which populates the background when set to true. When you change any of the "true," the background gradient that I want appears, but I have been trying to get it to update on the corresponding page link that's visited.

If anyone can guide me in the correct direction, I'd be very grateful.

Here's my header code:

/components/header.js

I've also made a layout component component and wrapped it in my _app.js.

Here's the rest of the code for other components:

_app.js

/components/layout/main.js

My Navbar currently looks like this: Navbar Image

If you need my other code, I am happy to provide. 😁

Upvotes: 1

Views: 4561

Answers (1)

adrianmanduc
adrianmanduc

Reputation: 896

Rather than storing current in the navigation array you could compute it each render based on the current url using router.asPath (see the docs here).

const isActive = router.asPath === item.href;

--

{
  navigation.map((item) => {
    const isActive = router.asPath === item.href;
    return (
      <NextLink key={item.name} href={item.href} passHref>
        <a
          className={classNames(
            isActive
              ? "text-black font-bold bg-gradient-to-r from-pink-300 via-purple-300 to-indigo-400"
              : "text-gray-700 hover:bg-gray-200 hover:text-gray-500 hover:underline hover:underline-offset-2",
            "px-3 py-2 rounded-md text-sm font-medium font-mono"
          )}
        >
          {item.name}
        </a>
      </NextLink>
    );
  });
}

Upvotes: 3

Related Questions