Be A React Dev

Gatsby’s Wrap Page Element

19-May-2023


Amazon Prime

gatsbyjs plus javascript

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

This means that you’ll want to add the wrapPageElement 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 wrapPageElement customised.

The wrapPageElement is for layout. What is not as clear is that it is for routing also. But setting up for routing is tricky because the documentation I find is unclear on these points.


gatsby-ssr.js

import CustomPage from './wrap-page-element';

export const wrapPageElement = CustomPage;

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

/* eslint-disable react/jsx-props-no-spreading */
import React from 'react';
//  routes and layout
import Layout from './src/content-layout';
import Routes from './src/security/routes';

const wrapPageElement = ({ element, props }) => {
  const { location } = props;

  return (
    <Layout {...props}>
      <Routes element={element} location={location} />
    </Layout>
  );
};

export default wrapPageElement;

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 four

Mom’s little shits times four

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


About

The Author Guy

Find Me

Rob Welan <rob.welan@beareact.dev>FacebookKo-FiLinkedInMediumPatreonRSS FeedStack OverflowX

Tech In Use

Be A React Dev

© 2024 Be A React Dev. All rights reserved.