Skip to content
Advertisement

Conditional link styling React

I want my nav bar to style the page title I’m in, im using React and Tailwind CSS, for example, just make the title yellow when im on the selected path.

My logic to achieve that would be this but isn’t working:

<div className={active ? "text-yellow-400" : undefined}

My rout code:

const LinkItem = ({href, path, children, ...props}) => {
    const active = path === href
    return (
        <NextLink href={href}>
            <div className={active ? "text-yellow-400" : undefined}
                {...props}
            >
                {children}
            </div>
        </NextLink>
    )
}

Nav bar code:

const Navbar = props => {

    const {path} = props

    return (
           <LinkItem href="/page1" path={path}>
               Page 1
           </LinkItem>
           )
}

Advertisement

Answer

Well at the end the problem was the path variable which was undefined, and wasn’t able to match href, so the condition never met.

Solution: call the path from useRouter hook with parameter .asPath, this gives me back the parameter which i stored in my path variable.

Code:

import NextLink from 'next/link'
import {useRouter} from "next/router";

const LinkItem = ({href, children, ...props}) => {
    const path = useRouter().asPath
    const active = path === href
    return (
        <NextLink href={href}>
            <div className={active ? "<styles here>" : "<styles here>"}
                {...props}
            >
                {children}
            </div>
        </NextLink>
    )
}

Nav bar code:

const Navbar = props => {

    const {path} = props

    return (
           <LinkItem href="/page1" path={path}>
               Page 1
           </LinkItem>
           <LinkItem href="/page2" path={path}>
               Page 2
           </LinkItem>
           )
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement