I’m using react-router-dom
version 6.3.0
and I’m trying to make my router handle an updated URL structure.
As an example, my old routes look like this:
<Route path='animals/dog' element={<Dog />} />
<Route path='animals/cat' element={<Cat />} />
<Route path='animals/bird/songs' element={<BirdSongs />} />
And I want them to automatically redirect without the root folder animals
:
<Route path='dog' element={<Dog />} />
<Route path='cat' element={<Cat />} />
<Route path='bird/songs' element={<BirdSongs />} />
Everything needs to redirect to where it previously went, but I don’t want to have to manually write a redirect for every possible Route
in my app.
Is that doable with React Router? In my situation, I’m not able to use .htaccess
or 301
redirects. It has to happen in React Router itself.
2
Answers
Seems like this was already answered: https://stackoverflow.com/a/43533070/14258470
Essentially you can specify a base URL.
Hopefully this helps!
Please give some more context if this isn’t the answer you’re looking for and I’ll adjust my answer to fit the OP better.
You can create a custom component to match any
"/animals/*"
route and redirect to the appropriate "root" route.Example:
Render
RedirectAnimals
route.