How To Deploy React App To GitHub Pages
If you’re a new web developer eager to showcase your React projects to the world, GitHub Pages is an excellent platform for hosting your apps for free. In this beginner’s guide, we’ll walk you through the step-by-step process of deploying your React app to GitHub Pages.
Prerequisites
Before we dive into the deployment process, make sure you have the following:
-
GitHub Account: If you don’t have one, sign up for a free account on GitHub.
-
Node.js and npm: Ensure that Node.js and npm (Node Package Manager) are installed on your computer. You can download them from the official website.
-
Git: Install Git, a version control system, from the Git website.
Create a React App
If you haven’t already, create your React app using Create React App:
npx create-react-app my-react-app
cd my-react-app
Replace my-react-app with your desired project name.
Initialize a Git Repository
Navigate to your React app’s directory and initialize a Git repository:
git init
git add .
git commit -m "Initial commit"
Push to GitHub
- Create a GitHub Repository:
- Visit the GitHub website.
- Click the ‘+’ icon in the top right corner and choose ‘New Repository’.
- Fill in the repository name and other details, then click ‘Create repository’.
- Connect Local Repository to GitHub:
- Follow the instructions on the GitHub repository page under the “…or push an existing repository from the command line” section.
Deploying to GitHub Pages
Now that your app is on GitHub, it’s time to deploy it to GitHub Pages.
- Install gh-pages Package:
Use npm to install the gh-pages package as a development dependency:
npm install gh-pages --save-dev
-
Update
package.json:Open your
package.jsonfile and add the following lines to the top-level:
"homepage": "https://githubusername.github.io/repo-name",
Replace githubusername with your GitHub username and repo-name with the name of your GitHub repository.
- Deploy Your App:
Add the following scripts to your package.json:
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
}
- Deploy Your App:
Now, deploy your app to GitHub Pages:
npm run deploy
- Visit Your Deployed App:
Your React app is now live! Visit it at https://githubusername.github.io/repo-name.
Troubleshooting
-
If you encounter any issues during deployment, double-check your configurations and ensure that your GitHub repository is set to ‘public.’
-
If you encounter a ‘404’ error when accessing your GitHub Pages URL, give it a few minutes to propagate.
Conclusion
Congratulations! You’ve successfully deployed your React app to GitHub Pages. This is a great way to share your web development projects with the world, and it’s especially valuable for new web developers looking to showcase their skills. Keep exploring and building, and don’t hesitate to share your creations with others. Happy coding!