I am in a pickle.
Im using React router v5. On my website I had page link as /pageName. Due to some new features, I changed the links to /:userId/pageName where userId is either "my" or user id. I am struggling to have the old links (/pageName) to redirect to /my/pageName, instead they redirect to /pageName/undefined. Another issue I am facing is that when it is at /pageName/undefined, when I click on pageName2 the url changes to /pageName/pageName2. How do I fix these linking issues? the param :userId should only be "my" for the user’s own account or diff user’s id.
I need this working in case user tries to just access /pageName like before, instead of /my/pageName. I would not want the linking to break
The below is how I render my Routes
export const routes: RouteItem[] = [
{
config: {
component: RedirectUser,
exact: true,
path: '/',
},
labelKey: '',
},
{
config: {
component: pageName1,
exact: true,
path: '/:userId/pageName1',
},
labelKey: 'pageName1',
navSection: 'top',
perm: 'READ',
},
{
config: {
component: pageName2,
exact: true,
path: '/:userId/pageName2',
},
labelKey: 'pageName2',
navSection: 'top',
perm: 'READ'
},
{
config: {
component: pageName2,
exact: true,
path: '/:userId/pageName2/:item',
},
labelKey: 'pageName2',
perm: 'READ'
},
]
export const Routes = () => {
const renderRoutes = routes.map((route: RouteItem, index: number) =>
<Route key={index} exact={route.config.exact} path={route.config.path} component={route.config.component} />);
return(
<Switch>
...
{renderRoutes}
...
</Switch>
)
}
2
Answers
Having a
redirect
key in the config and rendering the routes based on that key might solve your problem.Considering you are using Router v5, here is the implementation:
You just need to add a redirect from the old route path
"/pagename"
to the new route path"/my/pagename"
in your router. Ideally you’d just render a<Redirect from="/pageName" to="/my/pageName" />
directly, but you could also integrate it with your currentroutes
configuration.Example: