Skip to content
Kenny Tran

01 - Hero

GatsbyJS: Add CSS When JavaScript Is Disabled

02 - Post

GatsbyJS: Add CSS When JavaScript Is Disabled

Problem

I want to add specific CSS styling to my Gatsby website for users with JavaScript disabled.

Solution

Add a no-js class to to target elements in CSS when JavaScript is disabled and remove this class if JavaScript is enabled.

Add no-js Class to the Body Element

To add a class to in Gatsby, I needed to alter the contents of the static HTML file as it's being rendered and one way of doing so is to use the Gatsby Server-Side Rendering (SSR) API.

I created the file gatsby-ssr.js in the root of my Gatsby project, this file will allow me to hook into the SSR APIs.

I added the following block of code to the gatsby-ssr.js file

exports.onRenderBody = ({setBodyAttributes}) => {
    setBodyAttributes({
        className: 'no-js',
    });
};

Here I used the onRenderBody API and the setBodyAttributes object to set the className prop. You can read more about this on the Gatsby documentation website

Replace no-js Class If JavaScript Is Enabled

Now that I can target elements when JavaScript is disabled with the no-js class, I want to remove this class if JavaScript is enabled. I needed to hook into another one of Gatsby APIs, this time I used the Gatsby Browser API.

I created the file gatsby-browser.js in the root of my Gatsby project and added the following block of code

exports.onClientEntry = () => {
    document.body.className = document.body.className.replace(
        /\bno-js\b/,
        'js'
    );
};

I used the onClientEntry API to replace the no-js class with js when the Gatsby browser runtime first starts. You can read more about this on the Gatsby documentation website

And that's it! I can now target elements in CSS when JavaScript is disabled:

body.no-js .c-header {
    opacity: 1;
}

Available for new projects in April 2020