React-router: Remove inactive classes from NavLink

Created on 14 Mar 2020  路  5Comments  路  Source: ReactTraining/react-router

Using the NavLink component, I'd like to remove classes that should not be on an active link.

I'm using Tailwind and text-gray-200 does not override text-gray-800 when it is added to the element. I would like the class text-gray-800 to not be present while the link is active. Perhaps an inactiveClassName prop. I'd be happy to start a PR with some guidance.

What I've tried:

<NavLink
  to="/"
  className="px-3 py-2 text-gray-800"
  activeClassName="rounded-sm text-gray-200 bg-blue-gray-dark"
>
  Dashboard
</NavLink>

Could be:

<NavLink
  to="/"
  className="px-3 py-2"
  inactiveClassName="text-gray-800"
  activeClassName="rounded-sm text-gray-200 bg-blue-gray-dark"
>
  Dashboard
</NavLink>

Most helpful comment

@timdorr Yeah, I end up doing that usually but IMO it would be cleaner to only be applying the classes used on an element.

Appreciate the quick response!

All 5 comments

You can just disable the !important declarations: https://tailwindcss.com/docs/configuration/#important

Then the text colors won't be overridden by their order in the CSS file.

@timdorr, that setting is disabled by default. I tried false, true, and '#root' with no effect.

This has been discussed at https://github.com/tailwindcss/tailwindcss/issues/1010.

If you are trying to dynamically toggle between p-0 and p-4 you should always swap them out, toggle both, you shouldn't rely on css source order.


After doing some research, the class order defined on an HTML element has no effect, what matters is specificity. Since these two classes have the same specificity, the one that comes later in the stylesheet takes precedence.

https://stackoverflow.com/questions/12258596/class-overrule-when-two-classes-assigned-to-one-div/12258654

@timdorr Is this something you'd be willing to reconsider? I totally get adding extra bloat that doesn't make sense, but as I've been using tools like Tailwind CSS more recently as well it can become necessary to remove classes in "inactive" situations.

You can use @apply to create custom component classes from your Tailwind classes that better match the behaviors here.

@timdorr Yeah, I end up doing that usually but IMO it would be cleaner to only be applying the classes used on an element.

Appreciate the quick response!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stnwk picture stnwk  路  3Comments

Waquo picture Waquo  路  3Comments

ackvf picture ackvf  路  3Comments

sarbbottam picture sarbbottam  路  3Comments

andrewpillar picture andrewpillar  路  3Comments