I built my website with React and React Router and it is hosted on Github Pages. When I refresh the site on a page that is not my home page OR do ctrl+click to open the page in a new tab, it leads to a 404 error. I know this is because Github pages doesn't have access to front-end routes and one solution is to add a 404.html file that redirects back to your index.html.
I tried following the instructions on both
but neither worked for me. I think I am missing something but I can't figure out what is going wrong as I'm not that familiar with React Router. Can anyone help? (Note: I know a solution is to use HashRouter but I don't want my URLs to look ugly)
My code can be viewed on GitHub: https://github.com/christinexlin/portfolio
If you saw 404 even everything looks right, try switching https/http. The original question has the url wrong, usually you can check repo settings and found the correct url for generated site.
An alternative way to handle 404 page not found in React router is to redirect the user to a different page when they try to go to a page that doesn't exist. Copied! In the example, instead of rendering a PageNotFound component, we redirect the user to / if they go to a route that doesn't exist.
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.
I've spent quite some time to fix this issue. The issue is that GitHub Pages doesn't support single page apps, so there is a 404 error when refreshing page.
Check this out https://github.com/rafgraph/spa-github-pages and follow instructions, it is pretty straightforward. I've followed "basic instructions", but take a look at step 5 in "detailed instructions", that helped me fix it completely (adding repo name to absolute path of assets in index.html and setting segmentCount to 1).
Take a look at my code https://github.com/milosrancic/reactjs-website . I haven't used HashRouter, I've used Switch. And also I've added 404.html file.
I hope this helps
To get this to work, all I did was add a step to my GitHub Pages deploy pipeline that copies index.html
to 404.html
and then let my router handle the rest.
Note that this will still result in the routes returning a 404 status so SEO or CLI pings will think that requests failed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With