REACT GitHub Pages

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

Try It Now

3. Add homepage to package.json

  1. Open your React project’s package.json file.
  2. Add a homepage field:
    "homepage": "https://<username>.github.io/<repository-name>"
    

    Try It Now

  • 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"

Try It Now

4. Update scripts in package.json

Add the following deployment scripts:

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

Try It Now

  • predeploy: Automatically builds the app before deploying.
  • deploy: Publishes the build folder to GitHub Pages.

5. Deploy Your App

Run the deploy script:

npm run deploy

Try It Now

5. Deploy Your App

Run the deploy script:

npm run deploy

Try It Now

This will:

  1. Build your app (npm run build).
  2. Publish the build/ folder to the gh-pages branch of your repository.

6. Configure GitHub Pages

  1. Go to your repository on GitHub.
  2. Navigate to Settings > Pages.
  3. Under Branch, select gh-pages and click Save.

Your app will now be live at:

https://<username>.github.io/<repository-name>

Try It Now

7. Handling React Router (Optional)

If you’re using React Router, GitHub Pages needs a workaround for proper routing.

  1. Add a _redirects file in the public/ folder with this content:
    /*    /index.html   200
    

    Try It Now

  2. Deploy again:
    npm run deploy
    

    Try It Now

8. Update Your App

After making changes to your app:

  1. Push your changes to the main branch:
    git add .
    git commit -m "Update app"
    git push origin main
    

    Try It Now

  2. Redeploy by running:
    npm run deploy
    

    Try It Now

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"
  }
}

Try It Now

10. Advantages of GitHub Pages

  • Free hosting.
  • Continuous deployment with GitHub Actions.
  • Custom domain support.