How to Host Your React App on GitHub Pages
GitHup Pages is a great place to host your app. People can go to a URL and have your active project running and they can test it and see how it works. This helps the users that don’t know how to pull your repo and run the app. It also makes it really easy for someone to see your app without any effort. Did I mention that it’s free?
First thing you’ll want to do is create your repo.
Next, you’ll want to create your React app and deploy it. You can run the commands in terminal/shell. You’ll then want to navigate to the directory of the app.
$ npx create-react-app github_pages_repo
$ cd github_pages_repo
After creating your React app you’ll want to push your initial commit.
$ git init
$ git add .
$ git commit -m "initialCommit"
$ git remote add origin https://github.com/username/github_pages_repo.git
$ git push origin master
Then you’ll want to install the gh-pages package.
npm install gh-pages --save-dev
For the next step, we’ll want to add a homepage value in the package.json in the React app. The format is http://{username}.github.io/{repo-name}
, where username
is your GitHub username, and {repo-name}
is the name of the GitHub repository. It should look similar to the line below.
“homepage”: “http://devchea.github.io/github_pages_repo"
Then add the predeploy and deploy property below.
"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"
},
Save all the changes and then run the command below to deploy.
npm run deploy
Once this has been successfully deployed, you’ll want to go to the GitHub repo in your browser. Click settings and scroll down until you reach the GitHub Pages section. Make sure that gh-pages branch is selected as the source and save it. You’ll be given a URL, which is the exact same one as the homepage property we created a couple of steps ago.
Done!