Ad

Why Is A Github Page Url Changing On Load, Causing The Public Resource Path To Be Incorrect?

- 1 answer

I have a React page made with create-react-app and I deployed it to github pages per the instructions here. It opens, but the resources on the public directory aren't being loaded. What seems to be happening is that during the page load, http://{name}.github.io/{repo} is being truncated to http://{name}.github.io, and so the relative path to the public directory is no longer correct at the point when the page attempts to load them. If I try to then reload the page with the url http://{name}.github.io I get a 404 error.

I could just alter the paths to make it work, but that feels like a hack. I want to know what's going on here and how I might fix it, if that's possible.

The code can be seen here: https://github.com/CBreakr/ATTCK_StarWars

Supplement to the answer: https://medium.com/@svinkle/how-to-deploy-a-react-app-to-a-subdirectory-f694d46427c1

Ad

Answer

It's a bit difficult to say without seeing your code. However it's likely that your react-router is not setup properly.

You should setup your router like this:

import { BrowserRouter as Router } from ‘react-router-dom’;

const routerBaseName = process.env.PUBLIC_URL;

ReactDOM.render(<Router basename={routerBaseName}>< App /></Router>, document.getElementById(‘root’));

Note the basename part - it should be set to your production url when you build the bundle (in this case: https://CBreakr.github.io/ATTCK_StarWars/)

it should be set to your localhost url when you are developing locally.

You can use .env files to set values for PUBLIC_URL (I believe with create-react-app you will have to change it to REACT_APP_PUBLIC_URL) for dev/prod environments respectively, see: https://create-react-app.dev/docs/adding-custom-environment-variables

Ad
source: stackoverflow.com
Ad