DEV Community

Cover image for Deploy a React App to GitHub Pages
Hidayt Rahman
Hidayt Rahman

Posted on

Deploy a React App to GitHub Pages

Let's deploy react application on GitHub by using GitHub Pages.

Prerequisites

You need to have Node, yarn, and npm installed on your machine. To check if they are installed, open up a terminal window and type the following:

npm -v
yarn -v
node -v
Enter fullscreen mode Exit fullscreen mode

If these commands print out a version number in the terminal, you are good to go. If not, you need to go ahead and install what is missing.

  • Node (contains npm)
  • Yarn

Am assuming you already have a GitHub account. if not create one

Let's start.


Create a project

To create a project, you need to type the following in the terminal:

npx create-react-app my-react-app
Enter fullscreen mode Exit fullscreen mode

Once the operation finishes, you will have a boilerplate React project, ready to go. To see if it works properly run the command:

cd my-react-app
Enter fullscreen mode Exit fullscreen mode

and run below command

yarn start or npm start

If everything runs properly, you will see a message in the terminal that says that your application is running on a local server at this address: http://localhost:3000

Your project is ready to deploy.


Deploy Project to GitHub

In order for us to be able to upload our built application to GitHub Pages, we first need to install the gh-pages package.

yarn add gh-pages
Enter fullscreen mode Exit fullscreen mode

OR

npm install gh-pages --save-dev
Enter fullscreen mode Exit fullscreen mode

This package will help us to deploy our code to the gh-pages branch which will be used to host our application on GitHub Pages.

To allow us to use the gh-pages package properly, we need to add two keys into scripts value in the package.json file:

"scripts": {
    "predeploy": "npm run build", 
    "deploy": "gh-pages -d build"
  }
Enter fullscreen mode Exit fullscreen mode

Next, we need to modify our package.json file by adding the homepage field

{
  "homepage": "https://<username>.github.io/my-react-app/",
}
Enter fullscreen mode Exit fullscreen mode

Replace <username> with your own username.

This is URL of your hosted app.

All Set!!! We are ready to go

To deploy our application, type the following in the terminal:

npm run deploy
Enter fullscreen mode Exit fullscreen mode

Running the command above takes care of building your application and pushing it to a branch called gh-pages, which GitHub uses to link with GitHub Pages.

Woohoo!!!!! 🥳

Access the link https://<username>.github.io/my-react-app/

Note: It can take few hours to publish for the first time.

Discussion (0)