Deploying a React App on GitHub Pages for Beginners

Author

Reads 696

A hand holding a smartphone displaying an app, surrounded by notes and a laptop.
Credit: pexels.com, A hand holding a smartphone displaying an app, surrounded by notes and a laptop.

Deploying a React app on GitHub Pages is a great way to share your project with the world.

First, you'll need to create a new repository on GitHub and link it to your local project. This can be done by running the command `git add .` and then `git commit -m "initial commit"`.

Having a good understanding of GitHub and Git is essential for this process.

Next, you'll need to create a new branch in your repository to deploy your app. This is done by running the command `git branch gh-pages` and then `git checkout gh-pages`.

Additional reading: Create React App vs Next Js

Getting Started

GitHub Pages offers free hosting for static websites, making it an ideal choice for deploying React applications.

To get started, create a GitHub repository first. This is the foundation of your project, and it's where you'll store all your code.

Here are the benefits of using GitHub Pages for deployment:

  • Free Hosting: GitHub Pages offers free hosting for static websites.
  • Easy Integration: Seamlessly integrate your GitHub repository with GitHub Pages.
  • Automatic Updates: Automatically update your live site by pushing changes to your repository.

By following these simple steps, you'll be able to deploy your React application on GitHub Pages and enjoy the benefits of free hosting, easy integration, and automatic updates.

Create a App

Credit: youtube.com, How to Make an App [in 2023]

Create a React app by running the command $ npx create-react-app my-app in your terminal. This will create a new folder named my-app that contains the source code of a React app.

The app will be written in JavaScript, but you can create one written in TypeScript by using the --template typescript flag. For example, $ npx create-react-app my-app --template typescript.

The newly-created folder is also a Git repository, which means it has version control enabled. This is useful for tracking changes to your code over time.

You can check the branch name in your repository by running $ git branch. If your branch is named main instead of master, you can replace all occurrences of master in the tutorial with main.

To navigate to the newly-created folder, simply run the command $ cd my-app in your terminal. This will change your current directory to the source code of your React app.

Here are the steps to create a React app:

  1. Create a React app using $ npx create-react-app my-app
  2. Use $ npx create-react-app my-app --template typescript to create a TypeScript app
  3. Navigate to the newly-created folder using $ cd my-app

Why Use

HTML and CSS code on a computer monitor, highlighting web development and programming.
Credit: pexels.com, HTML and CSS code on a computer monitor, highlighting web development and programming.

GitHub Pages is a fantastic choice for deploying your React application. It offers free hosting for static websites, making it an ideal choice for deploying React applications.

Here are the top reasons why you should consider using GitHub Pages for deployment:

  • Free Hosting: GitHub Pages offers free hosting for static websites.
  • Easy Integration: Seamlessly integrate your GitHub repository with GitHub Pages.
  • Automatic Updates: Automatically update your live site by pushing changes to your repository.

With GitHub Pages, you can have your live site up and running in no time.

Prerequisites and Setup

To set up a React app on GitHub Pages, you'll need to meet some prerequisites. You'll need Node and npm installed on your computer, with versions 16.13.2 and 8.1.2 respectively.

You'll also need Git installed, with version 2.29.1.windows.1. And, of course, you'll need a GitHub account to host your app.

Here are the specific versions and tools you'll need:

Once you have these prerequisites met, you'll be ready to start setting up your React app on GitHub Pages.

Prerequisites

To get started with this tutorial, you'll need to meet a few prerequisites.

Node and npm are the first things you'll need. Make sure you have Node version 16.13.2 or higher installed, as well as npm version 8.1.2 or higher. Installing npm will also give you access to the npx command, which we'll be using later on.

Next, you'll need Git installed on your computer. You can check the version by running $ git --version in your terminal. I'll be using version 2.29.1.windows.1 in this tutorial.

Finally, you'll need a GitHub account to complete the steps in this tutorial.

Check Settings

IT professional working on a computer in a modern office setting, focused on coding and tasks.
Credit: pexels.com, IT professional working on a computer in a modern office setting, focused on coding and tasks.

Make sure your GitHub Pages settings are correct. Open up your GitHub repository and navigate to Settings > Pages.

To set up GitHub Pages, you need to choose a source. The source is where GitHub Pages will look for your files. You can choose from /(root) or /docs, but not a subfolder like /public.

One of the common repository configuration issues is GitHub Pages source not set correctly. Go to Settings > Pages and ensure the source is set to "Deploy from a branch" with "gh-pages" selected as the branch.

Here are some common repository configuration issues to check:

  • GitHub Pages source not set correctly
  • Missing permissions
  • Branch protection rules

If you're using GitHub Actions, make sure the workflow has the correct permissions to deploy to GitHub Pages. You can also check if branch protection rules are preventing deployment to the gh-pages branch.

Store Source Code

The source code of your React app is not yet stored on GitHub, which is why we need to commit the changes you made while following this tutorial to the master branch of the local Git repository.

Credit: youtube.com, How To Use GitHub For Beginners

To store the source code, you'll need to commit the changes you made while following this tutorial. Commit the changes you made while you were following this tutorial, to the master branch of the local Git repository.

You can use the following commands to commit and push the changes: $ git add . $ git commit -m "Configure React app for deployment to GitHub Pages" $ git push origin master.

The GitHub repository will now have two branches: master and gh-pages. The master branch will contain the React app's source code, while the gh-pages branch will contain the distributable version of the app.

Repository Configuration

Repository Configuration is crucial for hosting your React app on GitHub Pages. You must configure your repository to point to the correct location.

To set up your repository, you need to add a homepage property to your package.json file. This property follows the structure: http://{github-username}.github.io/{repo-name}. For example, if your GitHub username is "myusername" and your repo name is "my-app", the homepage property would be "homepage": "https://myusername.github.io/my-app".

Credit: youtube.com, Publish A React App To GitHub Pages - Less Than 3 Minutes

Common repository configuration issues include incorrect GitHub Pages source settings, missing permissions, and branch protection rules. Here are some potential problems to watch out for:

  • GitHub Pages source not set correctly
  • Missing permissions
  • Branch protection rules

To fix these issues, go to Settings > Pages and ensure the source is set to “Deploy from a branch” with “gh-pages” selected as the branch. Additionally, if using GitHub Actions, ensure the workflow has the correct permissions to deploy to GitHub Pages.

Create Empty Repository

Creating an empty repository on GitHub is a straightforward process. Sign into your GitHub account to begin.

To create a new repository, visit the Create a new repository form. Fill in the form with the required information, including the repository name and privacy type.

You can use any text editor you want to open the package.json file, but in this tutorial, we'll be using vi. Open the package.json file in a text editor and add a homepage property in the format https://{username}.github.io/{repo-name}.

Here's an example of how to add the homepage property:

  • "name": "my-app",
  • "version": "0.1.0",
  • "homepage": "https://gitname.github.io/react-gh-pages",
  • "private": true,

Navigate to the GitHub Pages settings page to configure the "Build and deployment" settings. Click on the "Save" button to save your changes.

Configure

From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio
Credit: pexels.com, From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio

To configure your repository, you'll need to set up GitHub Pages. This involves installing the gh-pages package, configuring the package.json file, and setting up your custom domain.

First, install the gh-pages package in your project. This package allows you to publish build files into a gh-pages branch on GitHub.

Next, configure the package.json file to point your GitHub repository to the location where your React app will be deployed. Add a homepage property that follows this structure: http://{github-username}.github.io/{repo-name}. For example: "homepage": "https://myusername.github.io/my-app".

You'll also need to add the predeploy and deploy scripts to the scripts section of your package.json. The predeploy script will build your React app, and the deploy script will publish the build folder to the gh-pages branch of your GitHub repository.

Here's an example of what the scripts section might look like:

```html

"scripts": {

"predeploy": "npm run build",

"deploy": "gh-pages -d build",

"start": "react-scripts start",

"build": "react-scripts build"

A software developer engaged in coding on dual monitors in a modern office setting.
Credit: pexels.com, A software developer engaged in coding on dual monitors in a modern office setting.

}

```

To configure your custom domain, you'll need to set up a CNAME file in your project. This file should contain the URL of your custom domain.

Once you've set up your custom domain, you can configure it in your GitHub Pages settings. Go to the settings menu, find "pages" under the code and automation tab, and type your custom domain URL into the "custom domain" text entry box.

Here are the steps to configure your custom domain:

1. Set up a CNAME file in your project with your custom domain URL.

2. Configure your DNS settings to point to the GitHub Pages URL.

3. Configure your domain in your GitHub Pages settings.

Here are the IP addresses of GitHub's servers that you'll need to configure in your DNS settings:

* 185.199.108.153

Deploying Your Application

Deploying your React app on GitHub Pages is a straightforward process. You can deploy your app in three quick steps if you already have a Create React App project and GitHub repository set up.

Credit: youtube.com, How To Deploy A React Vite App To Github Pages (Simple)

First, commit your changes and push them to your GitHub repository. Then, deploy your React application by running a specific command, which will create a bundled version of your app and push it to a gh-pages branch in your remote repository on GitHub.

To view your deployed React application, navigate to the Settings tab in your GitHub repository, click on the Pages menu, and you should see a link to the deployed app.

Here are the key steps to deploy your React app on GitHub Pages:

  1. Commit your changes and push them to your GitHub repository.
  2. Deploy your React application by running a specific command.
  3. View your deployed app by navigating to the Settings tab in your GitHub repository.

If you're using a custom domain, you may need to reconnect it under your GitHub account at Settings > Pages.

To automate the deployment process, you can use GitHub Actions. This streamlines the deployment process and enhances efficiency. You can create a workflow file in .github/workflows/deploy.yml to determine how to run the jobs. The workflow does the following:

  • Checkout repository — Fetches the code from your GitHub repository
  • Setup Node— Installs Node.js version 20 with npm caching for faster installations
  • Install dependencies — Installs the project dependencies using npm ci
  • Build— Builds the React application with any environment variables included
  • Deploy— Uses the JamesIves GitHub Pages deploy action to push the built files to the gh-pages branch

Once deployed, you can see the environment variable displayed on the page.

Troubleshooting

Credit: youtube.com, Resolving the Blank Screen Issue When Deploying a Routed React App to GitHub Pages

Troubleshooting your React app on GitHub Pages can be a challenge, but don't worry, I've got you covered.

Common repository configuration issues include GitHub Pages source not being set correctly, missing permissions for GitHub Actions, and branch protection rules that prevent deployment to the gh-pages branch.

If you're experiencing issues with relative links, try updating the PUBLIC_URL variable in your terminal to match your repo name by running `export PUBLIC_URL="/your-repo"`. This should fix root-relative links and resource links resolving to the wrong URL.

Here are some common issues to watch out for:

Page Refresh 404 Errors

If your app shows a 404 error when refreshing or accessing direct routes, you can try using HashRouter instead of BrowserRouter. This is because GitHub Pages doesn't support the browser history API.

Update your index.js file to use HashRouter and your URLs will change from /about to /#/about, which should resolve the 404 issues.

Alternatively, you can create a custom 404.html file that redirects to your index.html with the original URL parameters preserved.

For your interest: React Html Editor

Credit: youtube.com, React Refresh Page Not Found : Fix in 2 Minutes with This TRICK!

If you're still having trouble, make sure to check your repository configuration, as incorrect settings can cause 404 errors. Ensure the source is set to "Deploy from a branch" with "gh-pages" selected as the branch in the GitHub Pages settings.

Common repository configuration issues include:

Updating your relative links can also resolve 404 errors. Run the command export PUBLIC_URL="/your-repo" (replacing “your-repo” with your actual repo name) in your terminal to update PUBLIC_URL.

Check your homepage URL to ensure it matches your GitHub Pages URL format. This includes the username and repo name, like https://username.github.io/repo-name.

If your relative links are breaking in production, update them to use the PUBLIC_URL environment variable. This can be done by running export PUBLIC_URL="/your-repo" in the terminal, replacing "your-repo" with your actual repo name.

Inspect your page to see if relative links are resolving to the wrong path, like https://kathryngraysonnanz.github.io/favicon.ico, which returns a 404 error. This can happen when relative links are not correctly bundled.

Updating the PUBLIC_URL variable manually can resolve the issue, as seen in the example where running export PUBLIC_URL="/kendo-demo" fixed the problem.

Custom Domain and Hosting

Credit: youtube.com, How to Deploy Create React App to GitHub Pages? (Custom Domain & GitHub Actions)

To set up a custom domain for your React app on GitHub Pages, you'll need to purchase a domain name from a service provider like Namecheap or GoDaddy. This will allow you to connect your custom domain to GitHub Pages.

You'll need to create a CNAME record on your domain service provider that points to your GitHub username, like "username.github.io". This will direct visitors to your website.

To configure your custom domain, you'll need to set up DNS settings on your domain registrar. This involves creating a CNAME property that points to your GitHub Pages URL, like "http://your-username.github.io/your-repository-name". You'll also need to set up four A properties that direct your domain to GitHub's servers, which are located at IP addresses like "185.199.108.153".

In your React app project file, you'll need to create a CNAME file at the highest folder level that contains the URL of your custom domain. Once you've added, committed, and pushed the changes, re-run `npm run deploy` to configure your domain.

Credit: youtube.com, How To Use Custom DOMAIN With Github Pages For React JS App

To configure your domain with GitHub Pages, navigate to the settings menu, find "Pages" under the code and automation tab, and type your URL into the "Custom domain" text entry box. Wait for GitHub to check that your DNS settings align with the GitHub page you're trying to assign the custom URL to.

Here are the steps to configure your custom domain with GitHub Pages:

  1. Purchase a domain name from a service provider.
  2. Create a CNAME record on your domain service provider that points to your GitHub username.
  3. Set up DNS settings on your domain registrar, including a CNAME property and four A properties.
  4. Create a CNAME file in your React app project file with the URL of your custom domain.
  5. Configure your domain with GitHub Pages by typing your URL into the "Custom domain" text entry box.

Note that you may need to wait for GitHub to check that your DNS settings align with the GitHub page you're trying to assign the custom URL to.

Updating and Testing

To update your project, you'll need a GitHub account and familiarity with Git commands. You should also have Node.js 18+ installed, or you can install it here.

To create your project, you'll need to have a project created with Create React App (CRA). This will provide the necessary structure for your React app.

You'll also need to update your package.json. Here's a list of the requirements:

  • A GitHub account
  • Familiarity with Git commands
  • Node.js 18+ installed
  • A project created with Create React App (CRA)

Once you've updated your package.json, you can proceed with updating your GitHub Pages source and testing.

Update Source and Test

A young man with glasses drinks soda while working on his computer in a vintage office setting.
Credit: pexels.com, A young man with glasses drinks soda while working on his computer in a vintage office setting.

To update your Github Pages source, you need to return to the Github Pages settings and set your source to the gh-pages branch.

You'll also want to push everything up, if you haven't already, and deploy.

Check in Github to make sure that the gh-pages branch update, as this is a crucial step in the process.

Now, when you return to the Github Pages settings, you should be able to select gh-pages as your source branch.

Here are the requirements to have your Github Pages source updated and ready for testing:

  • A project created with Create React App (CRA)

At this point, you should be able to see something happening on your Github Pages URL – even if it’s not fully working just yet, it shouldn’t be the 404 error anymore.

Tips and Best Practices

When creating a React app on GitHub Pages, it's essential to follow some best practices to ensure smooth deployment and maintenance.

Use a custom domain to avoid the "github.io" suffix. This can be done by adding a CNAME file to your repository.

Credit: youtube.com, How to deploy a react application to GitHub Pages

Keep your app's dependencies up-to-date to avoid compatibility issues. This can be achieved by running `npm install` or `yarn install` before deploying.

Make sure to update your `package.json` file with the correct homepage and repository URLs. This helps GitHub Pages to correctly link to your repository.

Use a build tool like Webpack or Rollup to optimize your app's bundle size. This can significantly improve load times and overall performance.

GitHub Pages has a limit of 10,000 files in a repository. Be mindful of this limit when structuring your app's codebase.

Use a static site generator like Gatsby or Next.js to create fast and scalable web applications. This can be especially useful for large projects.

Frequently Asked Questions

How do I add a React app to a GitHub repository?

To add a React app to a GitHub repository, start by adding the GitHub Pages dependency packages and updating your package.json file. Then, push your code updates and deploy the application to view it on GitHub.

Ismael Anderson

Lead Writer

Ismael Anderson is a seasoned writer with a passion for crafting informative and engaging content. With a focus on technical topics, he has established himself as a reliable source for readers seeking in-depth knowledge on complex subjects. His writing portfolio showcases a range of expertise, including articles on cloud computing and storage solutions, such as AWS S3.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.