praks5432
praks5432

Reputation: 7792

React router with Gatsby

I currently have an application built with CRA which uses React Router. I'm now trying to have a part of my application be rendered via Gatsby so that non technical users can control the content of this part of the application via a CMS.

What I have currently works in the dev server, but dies when I try and build.

This is my gatsby-node

exports.onCreatePage = async ({ actions, page }) => {
  const { createPage } = actions;

  return new Promise((resolve, reject) => {
    if (page.path === "/") {
      createPage({
        ...page,
        matchPath: "/*"
      });
    }
    resolve();
  });
};

I have a static page that is being rendered at pages/study/index.js. It's quite large, so assume it looks like this

export default function Home({ data }) {
  if (!data) return null;

  const { mdx } = data;
  const { frontmatter: cmsData } = mdx;

  return (
    <StaticRouter location="/study">
      <Provider>
        <HomeTemplateWithRouter cmsData={cmsData} data={data} />
      </Provider>
    </StaticRouter>
  );
}

I also have an index.js which looks like this

import React from "react";
import { Provider } from "components/general/Provider";
import { BrowserRouter } from "react-router-dom";
import AppContainer from "containers/AppContainer";
import { StaticRouter } from "react-router";

const Application = () => {
  return (
    <BrowserRouter>
      <Provider>
        <AppContainer />
      </Provider>
    </BrowserRouter>
  );
};

export default Application;

Everything works when I use the development server. However when I build I get this error

Building static HTML failed for path "/"

See our docs page for more info on this error: https://gatsby.dev/debug-html


   7 | 
   8 |   if (isProduction) {
>  9 |     throw new Error(prefix);
     | ^
  10 |   } else {
  11 |     throw new Error(prefix + ": " + (message || ''));
  12 |   }


  WebpackError: Invariant failed

  - tiny-invariant.esm.js:9 invariant
    node_modules/tiny-invariant/dist/tiny-invariant.esm.js:9:1

  - history.js:250 createBrowserHistory
    node_modules/history/esm/history.js:250:115

  - BrowserRouter.js:29 new BrowserRouter
    node_modules/react-router-dom/es/BrowserRouter.js:29:176
  1. Why is this happening only when I build a production version of the website?
  2. Why is this happening given that I've defined a client side route and the code here should only be rendered client side?
  3. What is the way around this without changing my dependency on react-router?

Thanks!

Upvotes: 4

Views: 3274

Answers (1)

Champion
Champion

Reputation: 774

I have the same problem. I search on the Internet and find only one solution is to avoid react-router-dom.

Upvotes: 1

Related Questions