Next.js Conditional Styles
P粉596161915
P粉596161915 2023-08-10 16:17:51
0
1
596
<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粉596161915
P粉596161915

reply all(1)
P粉432930081

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 .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template