skip to Main Content

There’s multiple folders on a server that has different versions of my react app like:

data/www/demo1
data/www/demo2
...
data/www/demo15

Each folder contain the files copied (without changing anything) from a dist folder of my app.

I can access each version of the the app by url like:

http://server/demo1

When I added routing to my app this didn’t work anymore because I didn’t have basename in router:

root.render(
  <StrictMode>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<App />} />
          <Route path="attributes" element={<Attributes />} />
          <Route path="*" element={<InfoPage />} />
        </Routes>
      </BrowserRouter>
  </StrictMode>
);

How can I define the base so that it gets the folder that app files are located in? Of course I could hadcode the basename, build and copy stuff to a folder with that name, but I’d have to repeat that 15 times if I had 15 folders. Can I do it so that the folder name would be used as the basename?

2

Answers


  1. Chosen as BEST ANSWER

    This can be done by changing to HashRouter. The main difference is that /attributes route is accessed with different url like below:

    https://demo-machine.com/demo1/#/attributes
    

    The code looks like this:

    root.render(
      <StrictMode>
          <HashRouter>
            <Routes>
              <Route path="/" element={<App />} />
              <Route path="/attributes" element={<Attributes />} />
              <Route path="*" element={<InfoPage />} />
            </Routes>
          </HashRouter>
      </StrictMode>
    );
    

  2. The router takes a basename prop for just this scenario.

    basename

    Configure your application to run underneath a specific basename in
    the URL:

    function App() {
      return (
        <BrowserRouter basename="/app">
          <Routes>
            <Route path="/" /> {/* 👈 Renders at /app/ */}
          </Routes>
        </BrowserRouter>
      );
    }
    

    Add the appropriate basename URL path to each app’s router.

    Example:

    data/www/demo1
    
    <BrowserRouter basename="/demo1">
      <Routes>
        <Route path="/" element={<App />} />                 // "/demo1/"
        <Route path="attributes" element={<Attributes />} /> // "/demo1/attributes"
        <Route path="*" element={<InfoPage />} />            // "/demo1/*"
      </Routes>
    </BrowserRouter>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search