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.
2
Answers
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
Check your console logs, there is a warning regarding the
basename
prop and why nothing is rendered:Complete error:
The sandbox is served from
"/"
so there is a mismatch between it and the memory router’sbasename
prop and so the router won’t render anything. When you build and deploy the app and serve/host it from some".../web"
sub-directory thebasename
prop should work as you are expecting.If you want, you could probably conditionally apply which
basename
value to use depending on the build type.Example:
Note that in the sandbox it’s
process.env.NODE_ENV
that you would reference.