Home > Net >  Active nav item on click tailwind css in react
Active nav item on click tailwind css in react

Time:09-12

i have 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 change nav item when i clicked it but every where in stacksiverflow i search, saw nestjs, nextjs,... expect reactjs

CodePudding user response:

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

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

CodePudding user response:

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