react-snap and react-router together make a problem

8.1k views Asked by At

I need to start a react application and I need pre-rendering and routing, so I installed react-snap and react-router. (The react-router to do the routing and react-snap for pre-rendering obviously).

Everything looks fine in the local with 'npm start' but as I make a production build and serve it, the routing links make the page redirect to a new url, so all i see always, is the homepage.

My render looks like this:

 render() {
    return (
      <Router>
        <React.Fragment>
          <MainNav/>
          <Route exact path="/" component={Home}/>
          <Route path="/greeting/:name/:surname" render={(props) => <Greetings text="Hello, " {...props} />} />
          <Route path="/About" component={About}/>
        </React.Fragment>
      </Router>
    );
  }

and this is my index.js as suggested by react-snap

import React from 'react';
import { hydrate, render } from "react-dom";
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

const rootElement = document.getElementById("root");
if (rootElement.hasChildNodes()) {
  hydrate(<App />, rootElement);
} else {
  render(<App />, rootElement);
}

serviceWorker.unregister();

any ideas?

2

There are 2 answers

0
JoelMercurio On

I've been battling this for a couple weeks now. The main thing I've noticed is that if I call registerServiceWorker() in index.js, the app will function normally after building. If I comment out this line the app only routes to '/' no matter what.

It appears you are unregistering the service worker in your index.js, this might cause an issue.

A catch 22 I've run into and haven't been able to solve is that if I use the registerServiceWorker() call in index.js, react-snap doesn't properly prerender all the routes, and if I do comment out the registerServiceWorker() line, react-snap prerenders all routes perfectly, but the app doesnt navigate.

It's also worth noting that my project was created using 'create-react-app' and hasnt been ejected.

1
olecve On

I've been able to fix a similar issue by adding the following snippet to my package.json

"reactSnap": {
  "fixWebpackChunksIssue": false
}

Check the following link for more information and other options

https://github.com/stereobooster/react-snap/issues/264