Styling Navlink using Tailwind css
Asked Answered
Q

5

5

I am trying to add tailwind-css to Navlink(react-router-dom). I want to add active style. To add active styles I can use

<NavLink to="/faq" activeStyle={{fontWeight: "bold",color: "red"}}>
  FAQs
</NavLink>

Is there a way to do this with tailwind-css, I don't want to use css, maybe something like this?

<NavLink to="/faq" className={`${active?'font-bold text-red':'text-gray-900'}...`}>
  FAQs
</NavLink>
Quicksand answered 25/3, 2021 at 9:18 Comment(0)
P
9

V6 of React Router does not have the activeClassName property anymore. Here's how to style NavLink with Tailwind with the new version of ReactRouter and Remix

 <NavLink
    to="tasks"
     className={({ isActive }) =>
         isActive ? activeClassName : undefined
        }
     >
     Tasks
  </NavLink>

Taken from here https://remix.run/docs/en/v1/api/remix#navlink

Pestiferous answered 23/6, 2022 at 0:15 Comment(2)
why the need to use Remix I dont get it?Azov
@StevenAguilar Remix isnt a requirement, it just that the code snippet is from Remix's docs. Work the same for React.Control
U
5

NavLink component has an activeClassName property.

https://reactrouter.com/web/api/NavLink

Upcountry answered 25/3, 2021 at 9:28 Comment(1)
v6 of ReactRouter no longer has this :(Onstad
F
5

Recently I've been using that aria attribute that NavLink create when it's the current page:

<NavLink
  className="text-white aria-[current=page]:text-blue-400"
  to="/"
>
  Home
</NavLink>
Fatherless answered 19/4, 2023 at 5:6 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Istic
Perfect. I was looking for a simple solution to work with react js and Gatsby js and this is it.Stalwart
P
0

you can use

use: .active

the .active class will be applied automatically to the NavLink component when it matches the current URL path.

example

.active {
      @apply text-red-600 ....
 }
Plano answered 20/2 at 10:17 Comment(0)
B
0

NavLink automatically adds a class called active to the link. Add group class from Tailwind to NavLink. Then you can use group-[.active]: Tailwind modifier to selectively style the active links.

example:

<NavLink to="/home" className="group">
    <span className="group-[.active]:underline">Home</span>
</NavLink>

https://reactrouter.com/en/6.26.2/components/nav-link#default-active-class

https://tailwindcss.com/docs/hover-focus-and-other-states#arbitrary-groups

Braid answered 17/9 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.