GitHub Pages is a free and reliable way to deploy React applications. Follow these steps to get your React app live on GitHub Pages:
1. Prerequisites
- A GitHub account.
- A React project already created (e.g., using Create React App).
- A GitHub repository where you want to deploy your app.
2. Install gh-pages Package
The gh-pages package automates deployment to GitHub Pages. Install it in your React project:
npm install --save-dev gh-pages
3. Add homepage to package.json
- Open your React project’s
package.jsonfile. - Add a
homepagefield:"homepage": "https://<username>.github.io/<repository-name>"
- Replace
<username>with your GitHub username. - Replace
<repository-name>with the name of your repository.
Example:
"homepage": "https://john-doe.github.io/my-react-app"
4. Update scripts in package.json
Add the following deployment scripts:
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
predeploy: Automatically builds the app before deploying.deploy: Publishes thebuildfolder to GitHub Pages.
5. Deploy Your App
Run the deploy script:
npm run deploy
5. Deploy Your App
Run the deploy script:
npm run deploy
This will:
- Build your app (
npm run build). - Publish the
build/folder to thegh-pagesbranch of your repository.
6. Configure GitHub Pages
- Go to your repository on GitHub.
- Navigate to Settings > Pages.
- Under Branch, select
gh-pagesand click Save.
Your app will now be live at:
https://<username>.github.io/<repository-name>
7. Handling React Router (Optional)
If you’re using React Router, GitHub Pages needs a workaround for proper routing.
- Add a
_redirectsfile in thepublic/folder with this content:/* /index.html 200
- Deploy again:
npm run deploy
8. Update Your App
After making changes to your app:
- Push your changes to the main branch:
git add . git commit -m "Update app" git push origin main
- Redeploy by running:
npm run deploy
9. Example package.json
Here’s an example of a package.json configured for GitHub Pages:
{
"name": "my-react-app",
"version": "0.1.0",
"private": true,
"homepage": "https://john-doe.github.io/my-react-app",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
},
"devDependencies": {
"gh-pages": "^5.0.0"
}
}
10. Advantages of GitHub Pages
- Free hosting.
- Continuous deployment with GitHub Actions.
- Custom domain support.