In this shot, we will go over six easy steps to share your React app for free using GitHub Pages.
Create a public GitHub repository for your React app.
You need to create a GitHub account if you haven’t already.
Make a note of your owner and repository name in GitHub.
Go to homepage
, and make its value something like such as
http://<owner-name>.github.io/<app-name>/
.
In this example, it will be:
{
"homepage": "http://youssefzidan.github.io/gh-pages-app/",
"name": "gh-pages-app",
"version": "0.1.0"
//...
}
<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>;
}
Run the build command.
npm run build
You will find a newly created folder named “build.”
Rename the “build” folder as “docs.”
Go to repo settings => Pages section.
Pick your default branch. In my case, this will be “master.”
Change the /(root)
option to /docs
.
Wait a few minutes and you will see your app published on a URL like this:
https://youssefzidan.github.io/gh-pages-app/