Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4: Cant load page on GitHub pages

Locally I can browse to /buttons just fine I can even refresh it and its fine too, but when I upload the build directory to github pages I can't access /buttons and instead I get the GitHub 404 page, not my own 'notfound' page.

If I make a link from the home page to /buttons, then buttons will load, but browsing there directly it does not load.

import React, { useState } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { Context } from "./components/context";
import { Layout } from "./components/layout";
import { Home } from './routes/home';
import { Buttons } from './routes/buttons';
import { NotFound } from './routes/notfound';

const Router: React.FC = () => {

  const [global, setGlobal] = useState({
    language: localStorage.getItem("language") || 'en',
    apiUrl: 'https://api.domain.com/api',
    loggedIn: localStorage.getItem("jwt") ? true : false,
    redirectUrl: '',
    modal: false,
    modalState: '',
  });

  return (
    <Context.Provider value={{ global, setGlobal }}>
      <BrowserRouter basename={process.env.PUBLIC_URL}>
        <Route render = {({ location }) => (
          <Layout location = { location }>
            <Switch location = { location }>
              <Route exact path = '/' component = { Home } />
              <Route exact path = '/buttons/' component = { Buttons } />
              <Route component = { NotFound }/>
            </Switch>
          </Layout>
        )} />
      </BrowserRouter>
    </Context.Provider>
  );
}
export { Router };

In package.json I do have the homepage defined as:

"homepage": "https://myName.github.io/myRepo",

like image 820
Bill Avatar asked Oct 03 '19 23:10

Bill


People also ask

Can I use react router in GitHub pages?

So now we can deploy our react-router app to Github pages. You can refer to this GitHub repository for the deployment. Just make sure your homepage URL (project repository name) in package. json is the same as the homepage path.

Is react router deprecated?

Thus, we found that a lot of the packages were deprecated and needed to be replaced ASAP. One of the biggest surprises for us was the deprecation of react-router-redux .

What is the difference between HashRouter and BrowserRouter in react?

Both BrowserRouter and HashRouter components were introduced in React Router ver. 4 as subclasses of Router class. Simply, BrowserRouter syncs the UI with the current URL in your browser, This is done by the means of HTML-5 History API. On the other hand, HashRouter uses the Hash part of your URL to sync.

Does react-router-Dom reload the page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.

How do I use React router on GitHub Pages?

Using React Router on GitHub Pages. 1 Step 1: <BrowserRouter>. In either index.js or App.js — whichever has less clutter — import BrowserRouter as Router and wrap your main component with ... 2 Step 2: <Route> & <Switch>. 3 Step 3: <Link>. 4 Step 4: Direct URL Navigation and Hard Refresh.

Is it possible to load external JS files in react router V4?

This feature of loading external JS files should be by default in React router v4. As every application that is using React router needs the JS files loaded for every route. I am happy at least there is a solution to this issue.

How to import router tags from react router domain?

This will give you the ability to import the proper tags by placing "import { BrowserRouter as Router, Route, NavLink} from "react-router-dom";". There are a few more tags that can be added such as Switch, Link, useRouteMatch, and useParams, but I used Route and NavLink. (I'm sure there are a few more but I am not aware of them.) (1)

Does react-router have a Dom?

If you’re working on a React app that will run natively there is no DOM — instead you need the components specific to interacting with the native environment. You can find more details on the differences in the answers to this StackOverflow question: react-router vs react-router-dom, when to use one or the other?


1 Answers

As per deployment docs at https://create-react-app.dev/, for GH pages:

GitHub Pages doesn’t support routers that use the HTML5 pushState history API under the hood (for example, React Router using browserHistory). This is because when there is a fresh page load for a url like http://user.github.io/todomvc/todos/42, where /todos/42 is a frontend route, the GitHub Pages server returns 404 because it knows nothing of /todos/42.

If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:

  • You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to hashHistory for this effect, but the URL will be longer and more verbose (for example, http://user.github.io/todomvc/#/todos/42?_k=yknaj) Read more about different history implementations of react-router.

Change your routing from:


    <BrowserRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </BrowserRouter>

To:

import { HashRouter, Route, Link } from "react-router-dom";

...


    <HashRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </HashRouter>
...

  • Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your index.html page with a special redirect parameter. You would need to add a 404.html file with the redirection code to the build folder before deploying your project, and you’ll need to add code handling the redirect parameter to index.html. You can find a detailed explanation of this technique in this guide.
like image 185
pritam Avatar answered Sep 22 '22 19:09

pritam