Introduction
Why deploy a React app to GitHub Pages?
Prerequisites
Setting Up Your React App
Create a new React app using create-react-app
Configure your project
Installing gh-pages
What is gh-pages?
Installing gh-pages
Configuring package.json
Adding homepage field
Adding deployment scripts
Deploying Your React App
Running the deploy script
Verifying the deployment
Common Issues and Troubleshooting
Handling 404 errors for client-side routing
Updating the deployment
Advanced Configurations
Custom domain
Deploying from a specific branch
Conclusion
Recap
Further reading and resources
Introduction
Why Deploy a React App to GitHub Pages?
Deploying your React app to GitHub Pages is a quick and free way to share your work with others. It’s especially useful for showcasing projects, hosting documentation, or running simple static sites. GitHub Pages offers a straightforward process to get your React app online.
Prerequisites
Before you start, ensure you have the following:
A GitHub account
Node.js and npm installed on your machine
Basic understanding of Git and GitHub
Setting Up Your React App
Create a New React App
First, we’ll create a new React app using the ‘create-react-app’ command-line tool. Open your terminal and run:
npx create-react-app my-react-app
cd my-react-app
This will set up a new React project in the ‘my-react-app’ directory.
Configure Your Project
Make sure your project runs correctly locally. Start the development server:
npm start
Visit ‘http://localhost:3000’ to see your React app in action.
Installing gh-pages
What is gh – pages?
‘gh-pages’ is a npm package that makes it easy to deploy your project to GitHub Pages.
Installing gh-pages
Install the ‘gh-pages’ package as a development dependency:
npm install gh-pages --save-dev
Configuring package.json
Adding homepage Field
In your ‘package.json’ file, add a ‘homepage’ field. This tells React where your app will be hosted. Replace ‘yourusername’ and ‘yourrepository’ with your GitHub username and repository name:
"homepage": "https://yourusername.github.io/yourrepository"
Adding Deployment Scripts
Next, add the deployment scripts to ‘package.json’ under the ‘scripts’ section:
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
The ‘predeploy’ script runs automatically before ‘deploy’, building the app and creating the ‘build’ directory.
Deploying Your React App
Running the Deploy Script
To deploy your app, run the following command:
npm run deploy
This will create a new branch called ‘gh-pages’ in your repository and push the contents of the ‘build’ directory to it.