matt1331
matt1331

Reputation: 105

Tailwindcss isn't applying to NextJS Link component

I have a nextjs frontend project with tailwindcss installed.

In the following example code

import Link from 'next/link'

return(
  <div>

     <Link className="text-sm hover:text-gray-600" href="#">Test Link styling</Link>

     <a className="text-sm hover:text-gray-600" href="#">Test Link styling</a> 

  </div>
)

When inspecting element on the page, the anchor tag gets styled by tailwindcss but the anchor tag from the Link tag doesn't get any styling.

Does anyone know how to fix this? Does it require changing the tailwindcss configs?

Upvotes: 5

Views: 6077

Answers (6)

enguerran
enguerran

Reputation: 333

Starting from Next v13 you can directly add className to a next Link component. https://nextjs.org/blog/next-13#nextlink

To get back to the old behavior, you can add the legacyBehavior prop to the Link component:

Note, when legacyBehavior is not set to true, all anchor tag properties can be passed to next/link as well such as, className, onClick, etc. https://nextjs.org/docs/api-reference/next/link

Upvotes: 1

manuelkruisz
manuelkruisz

Reputation: 1702

Yes, that's because a Next.js Link doesn't accept a className property.

If you inspect the resulting HTML of your code, you will see that the resulting <a> tag will not have any of your classes on them.

For this to work properly you will need to put an anchor tag as a child to your Link:

<Link href="#">
    <a className="text-sm hover:text-gray-600">Test Link styling</a>
</Link>

Now next will not create an <a> tag for your Link, but instead, pass the href property to your existing <a> tag.

Upvotes: 0

A. Ahmad
A. Ahmad

Reputation: 536

Use a tag of HTML inside Link tag of next and give href inside Link.

<Link href="/support">
   <a className="rounded-lg p-3 duration-300 hover:bg-slate-200">
     Support
   </a>
</Link>

Upvotes: 1

goto type
goto type

Reputation: 1

you can use a a tag rather than a button tag. To make it work properly Link needs to have passHref prop.

Upvotes: 0

itsDanial
itsDanial

Reputation: 335

I put a button inside it cause idk why it styles better than an <a> tag

<Link href={"/" + props.id}>
    <button className="text-slate-900">Show Details</button>
</Link>

It gets the job done.

Upvotes: 2

Kristian Martinez
Kristian Martinez

Reputation: 174

Just put the a tag inside the Link tag without the href, leave href in Link and apply styles to the a tag. Like :

<Link className="text-sm hover:text-gray-600" href="#">
    <a className="text-sm hover:text-gray-600">Test Link styling</a>
</Link> 

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

Hope this helps and if you get a chance please upvote OnClick fires for another buttons click event

Upvotes: 9

Related Questions