36

How does one add a css class to a Link component in Next.js?

<Link
    className="app-subnav__link"
    href="/globalSettings"
>
    Settings overview
</Link>

It doesn't like the above! ES Link is throwing an error:

enter image description here

4 Answers 4

102

Try this (available in NextJS v13):

<Link href="/globalSettings" className="app-subnav__link"> 
    Settings Overview
</Link>

NextJS v12 and older:

<Link href="/globalSettings"> 
    <a className="app-subnav__link">Settings Overview</a>
</Link>

Reference: https://nextjs.org/docs/api-reference/next/link

Update: in NextJS v13 The next/link child can no longer be <a>. Add the legacyBehavior prop to use the legacy behavior or remove the <a> to upgrade. A codemod is available to automatically upgrade your code.


Any apps still using NextJS v12 or older should use the old approach, which was to give the Link an <a> child and style that:

<Link href="/globalSettings"> 
    <a className="app-subnav__link">Settings Overview</a>
</Link>
Sign up to request clarification or add additional context in comments.

1 Comment

you're right. My apologies - At first glance this looked very wrong but indeed it is the way to do it. Deleting my previous comment so as to not to confuses anyone...
6

In next version 13 you can use it directly in the Link component. Here is no need to include the a tag.

Comments

-2

apply the style to "a" also work for me

parentElement {
 a {
  padding:10px
 }
}

1 Comment

This doesn't answer the question OP has asked, as they want to specifically add a style to a single Link and then style it.
-4

enclose link inside a <div> . Apply className in the <div> . This might not be the right way to do it but it works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.