Ok, so I\'ve made a SPA using React and React-Router and have pushed it to github pages, but none of the routes I have written work when I refresh or click back in my browse
Aside from using hashHistory
as suggested in the accepted answer, there is another workaround. Look here.
Basically, you create a spoof 404.html
file which has a script that converts the requested path into the query string & redirects the browser to the index page with the query string attached to the URL. After the index file is loaded, the original path is restored from the query string & ReactRouter
picks up the changes.
A neat solution, but not production-ready, either.
To extend Jildert's answer, I did the same - copied index.html to 404.html before deploying to the github pages and it worked.
So I've just updated pre-deploy section of package.json to include this copy action and now it works fine with BrowserRouter:
"predeploy": "npm run build && cp build/index.html build/404.html",
"deploy": "gh-pages -d build"
If you are using create-react-app (I haven't tested this in any other environment) you can use browserRouter
, you will need to pass a basename
prop to the component with this env variable: process.env.PUBLIC_URL
.
Your router should now look like this:
<BrowserRouter basename={process.env.PUBLIC_URL}>
{/* routes */}
</BrowserRouter>
For more info you can checkout this Github thread
Use process.env.PUBLIC_URL in your route definitions so that they work both in development and after deployment. For example: . This will be empty in development and ... (inferred from homepage) in production.
I think you need to change your browserHistory to a hashHistory.. so you can use it with gh... it changes path from /home to #/home
I just found a solution for this without using the HashRouter. I created a little node script that's called before my deployment script that creates a 404.html file with the same content as the index.html. Github pages serves that file if you refresh on a page in your react-app.
const fs = require('fs')
fs.copyFile('build/index.html', 'build/404.html', (err) => {
if (err) throw err
console.log('index.html was copied to 404.html')
})