0
0
ReactHow-ToBeginner · 4 min read

How to Deploy React App: Simple Steps for Beginners

To deploy a React app, first run npm run build to create optimized static files in the build folder. Then, upload these files to a hosting service like GitHub Pages, Netlify, or Vercel to make your app live on the web.
📐

Syntax

Deploying a React app involves two main steps:

  • Build command: npm run build creates a production-ready version of your app in the build folder.
  • Hosting: Upload the build folder contents to a web host like GitHub Pages, Netlify, or Vercel.
bash
npm run build
Output
Creates a 'build' folder with optimized static files for deployment.
💻

Example

This example shows how to deploy a React app to GitHub Pages:

  • Install gh-pages package to help deploy.
  • Add deployment scripts in package.json.
  • Run npm run deploy to publish your app.
json
{
  "name": "my-react-app",
  "version": "0.1.0",
  "homepage": "https://yourusername.github.io/my-react-app",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1"
  },
  "devDependencies": {
    "gh-pages": "^5.0.0"
  }
}
Output
After running 'npm run deploy', your app is live at https://yourusername.github.io/my-react-app
⚠️

Common Pitfalls

Common mistakes when deploying React apps include:

  • Not setting the homepage field in package.json for GitHub Pages, causing broken links.
  • Uploading source files instead of the build folder contents.
  • Forgetting to run npm run build before deployment.
  • Using relative paths incorrectly, which breaks routing on some hosts.
json
Wrong (missing homepage):
{
  "name": "app",
  "scripts": {
    "deploy": "gh-pages -d build"
  }
}

Right (with homepage):
{
  "name": "app",
  "homepage": "https://username.github.io/app",
  "scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  }
}
📊

Quick Reference

  • Run npm run build to prepare your app for deployment.
  • Use gh-pages for GitHub Pages deployment.
  • Netlify and Vercel support drag-and-drop or Git integration for easy deployment.
  • Always test your deployed app URL to confirm it works correctly.

Key Takeaways

Run 'npm run build' to create optimized files before deploying your React app.
Set the 'homepage' field in package.json when deploying to GitHub Pages to fix paths.
Upload only the 'build' folder contents to your hosting service.
Use hosting services like GitHub Pages, Netlify, or Vercel for easy deployment.
Test your deployed app URL to ensure it works as expected.