search

Home  >  Q&A  >  body text

Next.js Conditional Styles

<pre class="brush:php;toolbar:false;"><p>I want to make the link valid if the path matches the link's href. </p> <pre><code> function Component() { const pathname = usePathname(); return ( <div className="links"> <Link href="/">Homepage</Link> <Link href="/store" className={`${pathname === this.href && "active"}`} >store</Link> <Link href="/actors">Actors</Link> </div> ) }</code></pre> <code> <p>I tried this but unfortunately it didn't work. Can I do something like this? </p></code></pre>
P粉596161915P粉596161915480 days ago585

reply all(1)I'll reply

  • P粉432930081

    P粉4329300812023-08-11 13:33:58

    You cannot use this in functional components that are only accessible within class components. To achieve the effect you want, you only need to write the code manually, for example:

    <Link href="/store" className={`${pathname === "/store" ? "active":""}`} >商店</Link>

    Also be careful not to use && in className, because if the condition is not true, it will add false to your className, so you can use the ternary operator to add "" when the condition is false .

    reply
    0
  • Cancelreply