How to deploy a react app to a subdirectory

Home >> Blog >> How to deploy a react app to a subdirectory
Let's suppose you are using create-react-app and react-router v4+.
  1. Define App Homepage
  2. Set Basename & Route Path
  3. Update the Links
1. Define App Homepage:

In package.json add homepage like below

{
  "name": "React App",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://domain-name.com/directory-name",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1",
    "react-helmet": "^5.2.1",
    "react-router-dom": "^5.1.2",
    "axios": "^0.19.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
2. Set Basename & Route Path:
<Router basename={'/directory-name'}>
  <Route path={`${process.env.PUBLIC_URL}/`} component={HomePage} />
  <Route path={`${process.env.PUBLIC_URL}/about.html`} component={AboutPage} />
  <Route path={`${process.env.PUBLIC_URL}/contact.html`} component={ContactPage} />
  <Route path={`${process.env.PUBLIC_URL}/blog.html`} component={BlogPage} />
</Router>
3. Update the Links:

In your code update urls of all the links/href etc.

<Link to={`${process.env.PUBLIC_URL}/about.html`}>About us</Link>
<Link to={`${process.env.PUBLIC_URL}/contact.html`}>Contact us</Link>
<Link to={`${process.env.PUBLIC_URL}/blog.html`}>My Blog</Link>

In public/index.html file set the PUBLIC_URL

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="stylesheet" href="%PUBLIC_URL%/style.css" />

Now, make new build using command - npm run build

After this, deploy build to the sub-directory from where you want to run react app, Enjoy!


TOP