Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a dynamic class to body tag in Gatsby.js?

Obviously, that's not an easy task, as the only thing that changes in the html.js template file by default are the head meta tags and the content.

The meta tags are handled by the Helmet component ({head.title.toComponent()} and {head.meta.toComponent()}) and the HTML changes inside the template are managed by React. (<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />)

The body tag however is outside the scope of React, which is why I can't figure out how to change it on-the-fly when I navigate from page to page. That's exactly what I'd need though as I wanna apply a different body background to each page.

I know that I could solve this by using the exports.onRouteUpdate in gatsby-browser.js, but I would like the class to be present even if JS is disabled in the browser. Means I'd like it to be there even if I export without the bundle.js file, just generating the static site HTML.

like image 542
Marcel Kalveram Avatar asked Dec 06 '16 12:12

Marcel Kalveram


People also ask

Can you add a class to a body tag?

You can also add a class to the body element when an event occurs, e.g. when a button is clicked.

Does Gatsby work without JavaScript?

:warning: The Gatsby javascript is only removed from the production build gatsby build and not during the dev build gatsby develop . If you do not write any state logic or event handlers then this should not effect you. This feature may be something this plugin wants to tackle in the future.


1 Answers

React-helmet now supports adding attributes to body element as well.

So, if you want to add a class to a specific component/page, you can do something like this:

import Helmet from 'react-helmet'  // Inside your component <Helmet     bodyAttributes={{         class: 'new-class-for-body'     }} />  // or  <Helmet>     <body className="new-class-for-body" /> </Helmet> 
like image 160
Moris.io Avatar answered Oct 12 '22 14:10

Moris.io