Highlight the active nav item on click using Tailwind CSS in React

Viewed 46

I have a navigation bar like this:

<nav className="bg-white shadow dark:bg-gray-800">
<div className="container flex items-center justify-center p-6 mx-auto text-gray-600 capitalize dark:text-gray-300">
        <Link
                to="/home"
                className="text-gray-800 transition-colors duration-300 transform dark:text-gray-200 border-b-2 border-blue-500 mx-1.5 sm:mx-6"
        >
                home
        </Link>

        <Link
                to="/invoices"
                className="border-b-2 border-transparent hover:text-gray-800 transition-colors duration-300 transform dark:hover:text-gray-200 hover:border-blue-500 mx-1.5 sm:mx-6"
        >
                features
        </Link>

        <Link
        
                to="/forms"
                className="border-b-2 border-transparent hover:text-gray-800 transition-colors duration-300 transform dark:hover:text-gray-200 hover:border-blue-500 mx-1.5 sm:mx-6"
        >
                forms
        </Link>

        <Link
                to="/newForm"
                className="border-b-2 border-transparent hover:text-gray-800 transition-colors duration-300 transform dark:hover:text-gray-200 hover:border-blue-500 mx-1.5 sm:mx-6"
        >
                form2
        </Link>
</nav>

I want to change the nav item when it's clicked, but everywhere in Stackoverflow that I've searched I only found solutions for NestJS, Next.js, etc., not React.

2 Answers

You should use active variant on className in tailwindCSS.
for example:

<Link
    to="/home"
    className="text-gray-300 active:text-blue-500"
>
    home
</Link>

You really need to define how you want to determine whether the class is added or not first.

Seems to me you'd want to instead loop through your items:


const isCurrentPage = (href: string) => {
   // return true if `href` is the current path, many ways you could do this
}

// loop through your items and conditionally add the class if active...
['/home', '/invoices', '/forms'].map(href => <Link key={href} href={href} className={isCurrentPage(href) ? 'active' : ''} />

Your isCurrentPage function depends on your app logic and setup; you could probably rely on some logic like window.location.pathname.indexOf(href) === 0 to start.

Related