Deploy your React App to GitHub Pages


You have created an awesome react app and want to show to host is as a demo. GitHub provides us a free hosting to host our static web apps. Lets take full advantage of GitHub pages to convert your react code repository into a website.

Step 1: Install the gh-pages package

You will need to install the gh-pages package as a “dev-dependency” of the app. Go to the root of your app folder in the command line then enter:

npm install gh-pages --save-dev

Step 2: Add homepage property

Open your package.json file in your react app and add homepage property. Set the value to be the string http://{username}.github.io/{repo-name} where username is your GitHub username and repo-name is the name of your repository you want the page to be installed. For example my homepage url for my skill-tree repository would be:

"homepage": "http://mattaisthorpe.github.io/skill-tree",

Step 3: Create the Deploy script

Back in our package.json file we can add deploy script commands. In the existing scripts property, add a predeploy property and a deploy property, each having the follwoing values:

  "predeploy": "npm run build",
  "deploy": "gh-pages -d build"

For example my scripts looks like:

  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

The predeploy command helps to bundle the react app for uploading while the deploy command uploads the bundled file to GitHub.

Step 4: Deploy to GitHub Pages

Next, Generate a production build of your app:

npm run predeploy

and deploy it to GitHub Pages

npm run deploy

Step 5: Setup repository source to the gh-pages branch

Once your deploy script has successfully deployed, open your GitHub code repository and click on the settings tab. Scroll down to the GitHub Pages section and choose gh-pages as the source.

And you are done! Your site is now accessible at the URL you specified for `homepage` up in step 2.