Adding style to active link with ActiveClassName and CSS Module in Gatsby is not working

2.2k views Asked by At

I'm facing an issue when I try to implement this:https://www.gatsbyjs.com/docs/gatsby-link/#add-custom-styles-for-the-currently-active-link using the ActiveClassName option.

I have created a navbar.js component which contains the links:

import React from "react";
import { Link } from "gatsby";

import navbarStyles from "./navbar.module.css";

export default function Navbar() {
  return (
    <nav className={navbarStyles.navbar}>
      <ul>
        <li>
          <Link to="/contact/" activeClassName="active">
            Contact
          </Link>
        </li>
        <li>
          <Link to="/blog/" activeClassName="active">
            Blog
          </Link>
        </li>
      </ul>
    </nav>
  );
}

and Styles are in a navbar.module.css (where I've defined a 'active' class) :

/* navbar */
nav ul li a {
    color: #FFF;
}
nav ul li a.active {
    color: #000;
}

My navbar link default color is correct #FFF My link is correctly updated with the active class when I go to the corresponding page, eg. :

<a aria-current="page" class="active" href="/contact/">Contact</a>

But .active style is never applied to the active link :( (Black color)

Strange thing here, when I extract the '.active' CSS from navbar.module.css and put it in my global.css file, things are working!

How can I make things work keeping my styles in the CSS modules?

Thanks for your help

2

There are 2 answers

4
Ferran Buireu On

Strange thing here, when I extract the '.active' CSS from navbar.module.css and put it in my global.css file, things are working!

Clearly, your styles are being overriten somewhere in your CSS code. Check the importation of the CSS assets and inspect the element to check from where is the current styling is taken (check the computed tab in the inspector).

Your code is perfectly valid and your CSS rule too, despite mixing CSS modules and CSS standard styling. You can also try something like:

      <Link to="/blog/" activeClassName={navbarStyles.active}>
        Blog
      </Link>
0
hakobpogh On

The problem is that you're using activeClassName="active" meanwhile you should be using the mapped class instead: activeClassName={navbarStyles.active}. And it seams that you don't have any class called navbar but you're trying to apply that style to the nav element: className={navbarStyles.navbar}.

But I suggest using patch-styles package, which introduces a more declarative way of applying styles. It's patching classNames instead of you.

You can use the PatchStyles with extraParams={'activeClassName'} to make it patch activeClassNames too. See the StackBlitz example for more details. (In the StackBlitz example click on the First Page link and see how the active style is being activated automatically).