Home > other >  Conditional link styling React
Conditional link styling React

Time:11-27

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>
           )
}

CodePudding user response:

Instead of undefined use either null or a empty string ""

Aswell. Use useState (not really needed in this scenario, but its always best to use in practice) https://reactjs.org/docs/hooks-state.html

CodePudding user response:

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>
           )
}
  • Related