DEV Community

Cover image for React Router not working after "React app" published through GitHub actions
Md. Azad Ul Kabir
Md. Azad Ul Kabir

Posted on

React Router not working after "React app" published through GitHub actions

If your React application is not working properly after being published on GitHub Pages, it's often related to the routing configuration. Here are a few common issues and their solutions:

1. Configuring React Router for GitHub Pages

GitHub Pages serves the index.html for all 404 responses by default, which means when using React Router, you need to ensure all routes fall back to index.html.

Solution
Add a 404.html file that contains the same content as your index.html file. This way, any invalid routes will serve your index.html and React Router will handle the routing.

2. Ensure the Correct homepage in package.json

Make sure you have the correct homepage field in your package.json. This helps with resolving the paths correctly.

{
  "name": "your-app",
  "version": "0.1.0",
  "homepage": "https://your-username.github.io/your-repo-name",
  ...
}
Enter fullscreen mode Exit fullscreen mode

3. Change the "private" property value in package.json

Change the private property value from true to false.

{
  "name": "your-app",
  "version": "0.1.0",
  "private": false,
}
Enter fullscreen mode Exit fullscreen mode

4. Need to add root path to the basename prop of BrowserRouter

If you are not using BrowserRouter, You need to add your root path to the basename prop of BrowserRouter

import {BrowserRouter} from 'react-router-dom'

ReactDOM.render((
   <BrowserRouter basename={process.env.PUBLIC_URL}>
     <App />
   </BrowserRouter>
), ...)  
Enter fullscreen mode Exit fullscreen mode

5. If BrowserRouter is not working use HasRouter

GitHub Pages doesn't support single-page applications (SPA) routing out of the box with BrowserRouter because it relies on client-side routing. A common workaround is to use HashRouter, which uses the URL hash to keep track of the route.

import { HashRouter } from 'react-router-dom';

ReactDOM.render(
  <HashRouter >
    <App />
  </HashRouter >,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

6. Check CNAME

If you are using a custom domain with GitHub Pages, ensure your CNAME file is correctly set up and included in your public directory.

my-app/
  public/
    index.html
    404.html
    CNAME (if using a custom domain)
  src/
    App.js
    index.js
  package.json
Enter fullscreen mode Exit fullscreen mode

Top comments (0)