Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
communitycreator

How to deploy a React app on GitHub pages

Youssef Zidan

In this shot, we will go over six easy steps to share your React app for free using GitHub Pages.

Step 1: Create a Github repository

Create a public GitHub repository for your React app.

You need to create a GitHub account if you haven’t already.

Creating Repo

Make a note of your owner and repository name in GitHub.

Step 2: Add a homepage key

Go to package.json and make a new key named homepage, and make its value something like such as http://<owner-name>.github.io/<app-name>/.

In this example, it will be:

package.json

{
  "homepage": "http://youssefzidan.github.io/gh-pages-app/",
  "name": "gh-pages-app",
  "version": "0.1.0"
  //...
}

Step 3: Wrap your routes inside <HashRouter basename="/">

If your app has routing, wrap your routes inside <HashRouter basename="/">. We need this step to prevent GitHub from redirecting your app to 404 in case you refresh the page.

import React from "react";
import {
  BrowserRouter,
  Switch,
  Route,
  Link,
  HashRouter,
} from "react-router-dom";

export default function App() {
  return (
    <BrowserRouter>
      <HashRouter basename="/">
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </HashRouter>
    </BrowserRouter>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

Step 4: Build your app

Run the build command.

npm run build

You will find a newly created folder named “build.”

Build Folder

Step 5: Change the name of the “build” folder to “docs”

Rename the “build” folder as “docs.”

Docs Folder

Step 6: Change repo settings

  • Go to repo settings => Pages section.

  • Pick your default branch. In my case, this will be “master.”

  • Change the /(root) option to /docs.

Alt Text

Wait a few minutes and you will see your app published on a URL like this:

https://youssefzidan.github.io/gh-pages-app/

RELATED TAGS

react
communitycreator
RELATED COURSES

View all Courses

Keep Exploring