How to Deploy a React app on GitHub pages?

M Hassaan Anjum
3 min readJun 18, 2023

--

  1. Initialize a Git repository: Open a terminal in the root folder of your React app and initialize a Git repository by running the following command:
git init

2. Create a remote repository: Go to GitHub (https://github.com) and create a new repository by clicking on the “New” button. Provide a name for your repository, choose the appropriate settings, and create the repository. Note down the repository URL for later use.

3. Add your files to the repository: Run the following command to add all files in your repository:


git add .

4. Commit the files: Commit the added files with a meaningful message using the following command:


git commit -m “Initial commit”

5. Set up the remote origin: Configure the remote origin for your Git repository using the repository URL you obtained earlier. Run the following commands, replacing `<githubUsername>` with your GitHub username and `<repositoryName>` with your repository name:


git branch -M main
git remote add origin https://github.com/<githubUsername>/<repositoryName>

6. Push your code to GitHub: Push the committed code to your GitHub repository using the following command:


git push -u origin main

7. Enable GitHub Pages: In your GitHub repository, navigate to the “Settings” tab, then scroll down to the “GitHub Pages” section. Select the “main” branch as the source and click “Save” to enable GitHub Pages.

You will see a link to your deployed website in the same section.

Using “REACT ROUTER” in your project?

8. Using React Router Dom: If you’re using React Router Dom in your project, follow these additional steps:

  • Install the `gh-pages` package as a dev dependency by running the following command:
npm install --save gh-pages

- Open the `package.json` file in your project and add the following lines in the appropriate places:

After the `”name”` key-value pair, add:


“homepage”: “https://<githubUsername>.github.io/<repositoryName>”,

Inside the `”scripts”` object, add:


“predeploy”: “npm run build”,
“deploy”: “gh-pages -d build”,

9. Deploy your project on GitHub Pages: To deploy your project, run the following command in your terminal:


npm run deploy

This command will create a `build` folder and deploy it to the `gh-pages` branch.

Note: If you have a pre-existing `build` folder, make sure to delete it before running the deploy command.

10. Verify deployment: After the deployment is complete, go to your GitHub repository’s “Settings” tab and scroll down to the “GitHub Pages” section. You should see your website’s link in this section.

By following these steps, you can deploy your React app on GitHub Pages and make it accessible to others.

ENJOY!!

--

--

M Hassaan Anjum

Passionate CS student always learning new stuff and sharing.