Search code examples
reactjsreact-router-dom

React Routers MemoryRouter does not work as expected when given a basename prop


For some reason, I struggle alot with getting the MemoryRouter to render Routes when I supply a basename prop to the url.

I made an example demonstrating what I mean here: https://codesandbox.io/p/sandbox/memory-router-woes-hmt5mn?file=%2Fsrc%2FApp.tsx

I want my router to render routes under the basename "/web" So, if the user visits "/web/" it should render PageOne. If a user hits "/web/list" it should render PageTwo.

I try to achieve this by configuring my MemoryRouter like this:

<MemoryRouter basename="/web">
        <Routes>
          <Route path="/" element={<PageOne />} />
          <Route path="/list" element={<PageTwo />} />
        </Routes>
</MemoryRouter>

The routes never render, and I just can't understand why. I am sure there must be something obvious/basic I am not seeing here.

Can you spot what I have missed?

I am using React Router v6.23.1

I tried to run this code without the basename prop and made sure to visit an url without the /web suffix. This works as expected. Once I add the basename prop and visit the url with the /web suffix, it will not render any of the routes.


Solution

  • After asking other people, one of my collegaues pointed out that this works as expected when the MemoryRouter is initialized with an 'initalEntries=["/web"]'

    I updated my sandbox to reflect it: https://codesandbox.io/p/sandbox/memory-router-woes-hmt5mn?file=%2Fsrc%2FApp.tsx