Deploy a React App with React Router on Github Pages for Free
In this article, I will show you how to deploy a React application to Github Pages quickly. I will also show you how to configure React Router to your application.
Prerequisites:
Make sure you have Github account and Git installed on your computer. Also, make sure node.js and npm are installed as well.
Step 1:
Create a React application using create-react-app.
npx install --save create-react-app my-app
cd my-app
npm start
Your application should now be running on http://localhost:3000.
Step 2:
Install gh-pages as a developer dependency.
npm install --save-dev gh-pages
Step 3:
Open your package.json file and add “homepage” at the top level. Add this value string “http://{YOUR-USERNAME}.github.io/{REPO-NAME}”
{
"homepage": "http://{YOUR-USERNAME}.github.io/my-app",
...
}
You will then need to add “predeploy” and “deploy” to your scripts. Add with the following values:
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
...
}
Step 4:
Create a public Github repository. Run the following commands to hook up your code to your new repository:
git init
git add .
git commit -m "initialize"
git remote add origin https://github.com/{YOUR-USERNAME}/my-app.git
git push -u origin master
Step 5:
Run npm run deploy in your terminal. It will deploy your app to Github Pages at https://{YOUR-USERNAME}.github.io./{REPO-NAME}.
If you make any additional changes after deploying, make sure you re-run npm run deploy to update the live page. You are all setup!
Bonus:
If you are using React Router, then BrowserRouter will not work for now. You can use HashRouter as an alternative.
// import { BrowserRouter as Router } from 'react-router-dom'
import { HashRouter as Router } from 'react-router-dom'
If you want to use BrowserRouter, then you can add basename={process.env.PUBLIC_URL} to Router.
<Router basename={process.env.PUBLIC_URL}>
<Switch>
...
Thank you for reading. If you have any questions about this (or anything JavaScript / React related), don’t hesitate to reach out! You can find me on Twitter @perezident14.