Luca Cimo
Luca Cimo

Reputation: 13

Change navigation styles depending on the current path Gatsbyjs

I am pretty new to Gatsby Js, I am quite struggling to understand how I can change my Header component styling based the current path. The Header component is common to all the pages but the styling should change slightly when I navigate to other pages like /portfolio and /team. Due to Gatsby SSR in production on the first page load when the path is "/portfolio or "team" the proper styling for the header doesn't change since the code to modify the className of the header component happens in the browser. Is there any way using the Browser API or SSR API to add/remove the correct className of the Header component? I hope I made it clear enough.

Upvotes: 1

Views: 725

Answers (1)

awran5
awran5

Reputation: 4546

Actually its easy. Gatsby comes with a handy plugin called react-helmet make sure you have it inside your package.json if you don't, check the Docs for installation.

All you need to do is to import helmet inside your targeted page for example portfolio.js

import { Helmet } from 'react-helmet'

After your <SEO> component, add Helmet component and define a CSS class within bodyAttributes element like so:

<Helmet bodyAttributes={{ class: 'portfolio-page' }} />

This will add portfolio-page class to the page body tag, and so, you can target that class like you would with regular CSS classes.

.portfolio-page .your-navigation {
   background-color: black;
}

Here is a codeSandbox for live example. Check page-2.js and components > layout.css

Upvotes: 3

Related Questions