react-router basename not working properly

2.6k Views Asked by At

I create a small react app withs this router:

<BrowserRouter basename='/hotel/'>
    <Routes />
</BrowserRouter>

and this are the routes:

<Switch>
    <Layout path="/:agency" component={Home} />
    <Layout path="/:agency/list" component={List} />
    <Layout path="/:agency/detail/:id" component={Detail} />
    <Route component={NoMatch} />
</Switch>

when I try to hit a route without the basename I get this warning on the console:



Warning: You are attempting to use a basename on a page whose URL path does not begin with the basename. Expected path "/4123" to begin with "/hotel"

while I'm expecting to get the nomatch route...is there a way to get the nomatch route instead of see my app?

1

There are 1 best solutions below

0
On

basename limits the router's application only to routes beginning with /hotel. What you need is to define the NoMatch at the root ("/") level, omitting the basename. Something like this:

<BrowserRouter>
  <Routes />
</BrowserRouter>

...

<Switch>
  <Layout exact path="/hotel/:agency" component={Home} />
  <Layout exact path="/hotel/:agency/list" component={List} />
  <Layout exact path="/hotel/:agency/detail/:id" component={Detail} />
  <Route path="*" component={NoMatch} />
</Switch>