Tailwindcss isn't applying to NextJS Link Tag

Viewed 1164

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?

4 Answers

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="#">Test Link styling</Link>
    <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.

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.

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

Related