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