Suyash
Suyash

Reputation: 1

React-router-dom + Suspense : Problem in gh-pages deployment

I am working on a React app which uses react-router-dom for routing alongside React.lazy() and Suspense for code-splitting.

It is the same gh-pages giving 404 error problem everyone had and when I encountered it before this, adding the basename prop to the BrowserRouter component would work. However, even after adding the basename prop, if I go to a certain route and refresh, the 404 page appears. Also if I directly access a route through the Browser, the 404 appears again.

My current workaround is to use HashRouter instead of BrowserRouter which doesn't let the app break in production. However, it puts hashes into the routes. Has anyone made the BrowserRouter work with Suspense in deployment on gh-pages or on any other deployment service? A suggestion for a better deployment option for the app is welcome.

Here are my routes in code and an example illustrating the issue:

import React, {Suspense} from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Fallback from "./components/Fallback"

const Carousel = React.lazy(()=>import("./components/carousel/Carousel"))
const Home = React.lazy(()=>import("./components/Home"))

function App() {
  return (
    <div className="App">
      <Router basename="/home">
        <Suspense fallback={Fallback()}>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/carousel" component={Carousel} />
          </Switch>
        </Suspense>
      </Router>
    </div>
  );
}

Here, if I go to the deployed site, (say URL: .github.io/home) I see the home page at /. Now if a link takes me to the /carousel route, I can see the carousel page but if I refresh, there are the 404 pages. Also if I directly access /carousel, the 404 pages again. I would love a workaround other than HashRouter which I'm already using.

Upvotes: 0

Views: 218

Answers (1)

Nitsan Cohen
Nitsan Cohen

Reputation: 697

I don't suggest deploying SPAs to gh-pages.

If you want a better service I would suggest using Netlify.

Go ahead and deploy your app it is really easy, I am sure that your problem will disappear.

www.netlify.com

Upvotes: 1

Related Questions