Gatsby wrapPageElement causing elements to render twice

Viewed 243

Using wrapPageElement in gatsby-browser.js and gatsby-ssr.js is causing header and footer elements to render twice.

gatsby-browser.js

import React from 'react';
import PageLayout from './src/components/layout/PageLayout';

export const wrapPageElement = ({ element, props }) => {
  // Wraps every page in a component
  return <PageLayout {...props}>{element}</PageLayout>;
};

gatsby-ssr.js

import React from 'react';
import PageLayout from './src/components/layout/PageLayout';

export const wrapPageElement = ({ element, props }) => {
  // Wraps every page in a component
  return <PageLayout {...props}>{element}</PageLayout>;
};

PageLayout.tsx

const PageLayout: FC =() =>{
   return (
     <PageWrapper>
         <Header/>
         <Footer/>
     </PageWrapper>
  );
};

I also have errors in these files on the return line but can't see what is causing the error

JSHint: Expected an assignment or function call and instead saw an expression.(W030)

Is there any alternatives or known causes of this?

1 Answers

This is because your pages should also be containing a Layout component wrapper so the header and the footer are added by the page itself plus the wrapPageElement.

If you need to use wrapPageElement, you should get rid of the Layout in the pages, otherwise, remove the wrapPageElement.

In your pages you can do:

const SomePage=()=>{
  return <>
   <div>Some dummy content</div>
  <>
}

Instead of wrapping it with the Layout component.

Regarding the other warning:

JSHint: Expected an assignment or function call and instead saw an expression.(W030)

It's impossible to guess with the provided details or seeing the whole app, could be anywhere but certainly it is not caused by the wrapPageElement wrapper.

Related