Deploy a React App with React Router on Github Pages for Free

Joseph Perez
2 min readJul 8, 2021

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Joseph Perez
Joseph Perez

Written by Joseph Perez

I am a software engineer working in EdTech. I have a passion for supporting those working hard to get into the tech industry.

No responses yet

Write a response