DEV Community

loading...
Cover image for Gatsby.js Browser APIs Explained: wrapPageElement vs wrapRootElement

Gatsby.js Browser APIs Explained: wrapPageElement vs wrapRootElement

crock profile image Alex Crocker ・2 min read

Gatsby.js is a powerful and flexible React framework that's focused on generating static pages and content from various external data sources at build time. It has a suite of powerful browser and node apis to manipulate data and create any page you might need.

Today I'm going to explain in-depth the difference between two fundamental browser apis that you should know, wrapPageElement and wrapRootElement.

Both of these browser apis are typically defined in the gatsby-browser.js file in the root of the project, but you can export both functions from gatsby-ssr.js as well in some cases without having to duplicate the code.

wrapPageElement is for layouts

First, the wrapPageElement api is ideal for base layouts that every page has. It's not necessary to use this function, but if you don't want to have to add your base layout component to every page of your site, then using this api is a good way to save some typing. Under the hood, this is what gatsby-plugin-layout is using, so now you can remove that unnecessary plugin.

wrapRootElement is for providers

Finally, the wrapRootElement api is designed for wrapping your core application with all of your various providers. In the example source code below, I am using the react-alert NPM package, which provides a convenient provider for us to demonstrate this api's usage. React Alert is a user-friendly library which provides hooks for customizing and displaying various alerts and notifications to the user.

To sum up, Gatsby has plenty of other browser apis, but wrapPageElement and wrapRootElement are the two you will probably be using most often in your sites. If you just remember that wrapPageElement is for layouts and wrapRootElement is for providers, you will be on your way to being a Gatsby expert in no time!

Source Code

import React from "react"

// Base Layout
import { Layout } from "./src/layouts/"

// react-alert
import { transitions, positions, Provider as AlertProvider } from "react-alert"
import AlertTemplate from "react-alert-template-basic"

const alertOptions = {
    position: positions.TOP_RIGHT,
    timeout: 5000,
    offset: "30px",
    transition: transitions.FADE,
}

export const wrapPageElement = ({ element }) => <Layout>{element}</Layout>

export const wrapRootElement = ({ element }) => (
    <AlertProvider template={AlertTemplate} {...alertOptions}>
        {element}
    </AlertProvider>
)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide