πŸš€ How to Deploy a React App to GitHub Pages (Step-by-Step Guide)

If you’ve built a React portfolio or project, the next big step is deploying it online so others can see it. One of the easiest free hosting options is GitHub Pages. In this guide, I’ll walk you through how to deploy your React app to GitHub Pages step by step.

βœ… Why Choose GitHub Pages?

  • Free hosting directly from your GitHub repository
  • Great for portfolios, personal projects, and documentation
  • Easy integration with React apps using gh-pages package

πŸ› οΈ Prerequisites

Before we start, make sure you have:

  • Node.js and npm installed
  • A React app (created with Create React App or Vite)
  • A GitHub account and a public repository

πŸ“Œ Step 1: Install gh-pages

In your project root folder, install the gh-pages package:

npm install gh-pages --save-dev

This package will help publish your build folder to GitHub Pages.

πŸ“Œ Step 2: Update package.json

Open your package.json file and add a homepage field:

"homepage": "https://<your-username>.github.io/<your-repo-name>"

Then, update your scripts section:

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

πŸ“Œ Step 3: Push Code to GitHub

If you haven’t already pushed your project to GitHub, run:

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/<your-username>/<your-repo-name>.git
git push -u origin main

πŸ“Œ Step 4: Deploy Your App

Run the deploy command:

npm run deploy

This will create a gh-pages branch in your repository, which GitHub Pages will use to serve your site.


πŸ“Œ Step 5: Configure GitHub Pages

  1. Go to your repository on GitHub
  2. Navigate to Settings β†’ Pages
  3. Under Source, select:
    • Branch: gh-pages
    • Folder: / (root)
  4. Save your changes

Your React app will now be live at:
πŸ‘‰ https://<your-username>.github.io/<your-repo-name>


πŸ”§ Common Issues & Fixes

  • Images not loading?
    Ensure you reference images correctly with process.env.PUBLIC_URL + "/images/your-image.png".
  • 404 on refresh (React Router)?
    Add a 404.html that redirects to index.html, since GitHub Pages doesn’t handle client-side routing by default.

🎯 Conclusion

Deploying a React app to GitHub Pages is simple and free. With just a few steps β€” installing gh-pages, updating package.json, and configuring GitHub Pages β€” you can share your portfolio or project with the world.

Now, go ahead and deploy your project today! πŸš€

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *