AliLynne

TIL #1 - Gatsby Link & activeClassName

2019-08-26

Tags:

Shelf of books

Gatsby Link and activeClassName

I've used the Link component from Gatsby before, but didn't know about activeClassName. For those who aren't familiar, Gatsby's Link component is used to create internal links in your Gatsby site. (If you need to link to an external source, just stick with an <a> tag.)

In this instance, I'm using it to navigate from the homepage to the Contact page of my website.

<Link to="/contact/">Contact</Link>

If I add a couple more links inside of an unordered list, I get a navigation menu:

<ul>
  <li>
    <Link to="/contact/">Contact</Link>
  </li>
  <li>
    <Link to="/about/">About</Link>
  </li>
  <li>
    <Link to="/">Home</Link>
  </li>
</ul>

The icing on the cake is adding a couple of classnames to each Link and a small amount of css.

<Link className="link" activeClassName="active-link" to="/contact/">Contact</Link>
.link {
  color: #000;
}

.active-link {
  color: #ba2d65;
}

With those two bits of additional code, our Contact link will now be pink when the current URL matches the Link's to prop exactly. We now have a simple navigation menu.

Photo by Jessica Ruscello on Unsplash

Hire Me!

I'm looking for a new position. Please check out my projects page, my technologies and skills and contact me at ali@alilynne.com if you're interested.

Support My Work

or

Buy Me a Coffee at ko-fi.com