How to use Gatsbys wrapPageElement with Typescript in a local plugin?

Viewed 202

I'm trying to create a new Gatsby plugin. I started with developing it as a local plugin. In this plugin I want to provide a wrapPageElement for server side rendering and during runtime, so I've create the following configuration files:

gatsby-ssr.js:

export { wrapPageElement } from "./src/wrapPageElement";

gatsby-browser.js:

export { wrapPageElement } from "./src/wrapPageElement";

src/wrapPageElement.tsx:

import React from "react";
import { GatsbyBrowser, GatsbySSR } from "gatsby";

type WrapPageElement =
  | GatsbyBrowser["wrapPageElement"]
  | GatsbySSR["wrapPageElement"];

export const wrapPageElement: WrapPageElement = ({ element, props }: any) => {
  return <div {...props}>{element}</div>;
};

Now when I run my Gatsby project I get the following runtime error:

One unhandled runtime error found in your files. See the list below to fix it:

Unknown Runtime Error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `PageRenderer`.
:

No codeFrame could be generated

When I don't try to render {element} within the wrapPageElement, for example a simple string, the wrapPageElement is successfully rendered. The problem seems to be related to element. Does somebody have an idea what is wrong here?

I'm on Gatsby version 3.14.0.

2 Answers

It seems to be unresolved (yet) according to this GitHub thread, where apparently types are not properly exported by Gatsby.

As a hacky workaround you can try:

type Fn = (...args: Parameters<WrapPageElement>) => ReturnType<WrapPageElement>

export const wrapPageElement: Fn = ({ element, props }: any) => {
  return <div {...props}>{element}</div>;
};

Note: modified from the source in the GitHub's thread

The problem was, that my page I tried to render didn't have a default export.

Instead of ..

import React from "react";

export default function IndexPage() {
  return <div>
    Index
  </div>
}

.. I defined ..

import React from "react";

export function IndexPage() {
  return <div>
    Index
  </div>
}

.. what caused the error.

Related