React Router

Last updated: 2020-05-04

Deploy To Subdirectory

  1. Convert all absolute links to relative ones. Base tag works only for relative URLs. In other words, it's required to replace all paths that start with / to ./. Conversion should be applied to all resources and assets. All assets should reside within the src folder.

    <body>
      <img src="./assets/logo.svg" />
    </body>
    
  2. Setup homepage in package.json to /subdir/

    "homepage": "/subdir/",
    
  3. Add <base href="%PUBLIC_URL%/"> to index.html. This tag should be placed in the <head> before any other element that uses URLS.

    <head>
      ...
      <base href="%PUBLIC_URL%/" />
      <title>React App</title>
    </head>
    <body>
      ...
    </body>
    
  4. Add router history package

    npm install --save history
    # or
    yarn add history
    
  5. Adjust the router

    import { createBrowserHistory } from 'history';
    ...
    export const history = createBrowserHistory({
      basename: process.env.PUBLIC_URL
    });
    
  6. Use updated history and basename in router

    <Router history={history} basename={'/subdir'}>
    

References