Home > Net >  React router doesn't handle urls containing more than one segment
React router doesn't handle urls containing more than one segment

Time:04-28

I am struggling to get react router v6 to work properly. Given the below:

<BrowserRouter>
  <Routes>
    <Route index element={<div>1</div>} />
    <Route path="home" element={<div>2</div>} />
    <Route path="user" element={<div>3</div>}>
      <Route path="profile" element={<div>3.1</div>} />
      <Route path="account" element={<div>3.2</div>} />
    </Route>
    <Route path="*" element={<div>4</div>} />
  </Routes>
</BrowserRouter>

The following paths do what I expect:

  • https://localhost:3000 renders 1
  • https://localhost:3000/home renders 2
  • https://localhost:3000/user renders 3
  • https://localhost:3000/other renders 4

The following paths do not do what I expect:

  • https://localhost:3000/user/profile renders a blank page rather than 3.1
  • https://localhost:3000/user/account renders a blank page rather than 3.2
  • https://localhost:3000/user/other renders a blank page rather than 4
  • https://localhost:3000/other/other renders a blank page rather than 4

I am aware that including <Outlet /> in the parent component (e.g. that rendered by /user) allows child components to render within it. However this only works with an index route. As soon as a second slash (e.g. /user/account) appears in the path, the request fails. Equally, the * default only renders if the unknown url contains a single /.

I must be doing something silly here since this example is essentially lifted from the instructions (Console error

CodePudding user response:

Check this working example in Codesandbox

CodePudding user response:

Thanks for the help! In the end I think my issue was tied up with using IIS and URL rewrite under the hood, which none of the examples (reasonably) consider.

I hadn't properly set up my web.config file (as per the answer here: https://stackoverflow.com/a/39968035/5181023) or index.html to handle extended urls and once I had, urls with multiple segments worked as expected.

  • Related