Search code examples
javascriptreactjsreact-router-domrelative-path

React Router Dom Relative Path


I have an application published in a domain similar to this "www.domain.com/app/client/store"

When I developed it at the beginning, it was not contemplated that the domain be that way but something like "www.domain.com" the issue is that it is causing problems with the Router

when you access the initial route "www.domain.com/app/client/store" it does not find the path that is the login and jumps to management

I need that regardless of the url always find the initial path which "/"

My router currently looks like this

const Routes = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Login} />
        <Route exact path="/main" component={Main} />
        <Route exact path="/main/:id" component={Main} />
        <Route exact="/management" component={Management} />
      </Switch>
    </Router>
  );
};

The domain will be relative so it is not a good idea to put the absolute URL in the path

How can I make the route relative and not affect the initial page of the application?

The routes would be more or less like this

"www.domain.com/app/client1/store5" "www.domain.com/app/client5/store1" "www.domain.com/app/client2/store3"

Thanks in advance for your help and feedback


Solution

  • In order to properly route, your path requires the public URL appended to every route.

    const baseURL = process.env.PUBLIC_URL;
    
    const Routes = () => {
      return (
        <Router>
          <Switch>
            <Route exact path="${baseURL}/" component={Login} />
            <Route exact path="${baseURL}/main" component={Main} />
            <Route exact path="${baseURL}/main/:id" component={Main} />
            <Route exact="${baseURL}/management" component={Management} />
          </Switch>
        </Router>
      );
    };
    
    
    

    Something like that should work. There are also packages out there you could use in order to make life easier that would automatically append this, But this is a pretty simple approach.