Gatsby’s Wrap Root Element

15-May-2023



gatsbyjs plus javascript

Gatsby’s wrapRootElement exists in both the browser and server side rendering APIs.

This means that you’ll want to add the wrapRootElement to both the gatsby-browser.js/ts file and to the gatsby-ssr.js/ts file.

This guide looks at the gatsby-ssr.js/ts file because once you know this one you can duplicate the code in the other file.

Note that the gatsby-browser.js/ts file and the gatsby-ssr.js/ts file must go in the same directory (the root) as the gatsby-config.js/ts file. Or it won’t work.

So here is an example gatsby-ssr.js/ts file which has the wrapRootElement customised.

The wrapRootElement is for providers. Putting other stuff in there beside provider definitions could cause a whiffy code smell.


gatsby-ssr.js

import CustomRoot from './wrap-root-element';

export const wrapRootElement = CustomRoot;

wrap-root-element.js (or could be .ts extension)

import React from 'react';
import { Provider } from 'jotai';
//  chakra-ui
import { ChakraProvider, ColorModeProvider } from '@chakra-ui/react';
//  theme
import theme from './src/@chakra-ui/gatsby-plugin/theme';

const wrapRootElement = ({ element }) => (
  <Provider>
    <ChakraProvider theme={theme}>
      <ColorModeProvider>{element}</ColorModeProvider>
    </ChakraProvider>
  </Provider>
);

export default wrapRootElement;

Updated 14-Jun-2023

I was today years old when I discovered in the @chakra-ui/gatsby-plugin documentation that you had to have the theme in a specific folder within the src folder. Or else you may as well not bother trying.

Last But Not Least

Oh, in case you were wondering, Jotai is a cool state management system which is easier to learn and use than Redux .

Chakra UI is a framework thingy to style up your website.

Both are sexy. Give them a try.


Get Cool Swag

If you are finding this content useful (or maybe you are just a nice person or maybe you just like my merch) I would be greatful if you headed over to my shop and make a purchase or two. All proceeds will go towards making more courses.

If there’s merch missing that you would like, let me know (click this: Make Something For Me ) and I’ll try to make it for you.

mom’s little shits times two

Mom’s little shits times two

You can buy this product or you can check out my shop of products.