'React router handling undefined routes in Multi Project React Application
I have a react application with a multi-project setup, where the first and the parent project has a set of routes defined and already have some Routers setup and In my child project, I had to handle unknown routes and show a 404 page, but the catch here is that the child project recognizes the routes from the parent project as unknown routes and shows the component for the route plus the 404 page.
In my child app, I have access to the list of routes in my parent project, so how can I handle that and prevent two components rendering on a single page
Parent Project
- Routes
- /route1 - RouteOneComponent (<Route path="/route1" component={RouteOneComponent} />)
- /route2 - RouteTwoComponent (<Route path="/route2" component={RouteTwoComponent} />)
- Child Project (props - parentProjectRoutes : ["/route1", "/route2"])
- /child-route-1 - ChildRouteOneComponent (<Route path="/child-route-1" component={ChildRouteOneComponent} />)
- /child-route-2 - ChildRouteTwoComponent (<Route path="/child-route-2" component={ChildRouteTwoComponent} />)
- * - Component404Page (<Route path="*" component={NotFoundPage} />)
I have also tried moving the NotFoundPage router logic to Parent Project but, the current routing situation of my application is sort of messed up, and the only way to solve this is through the child project.
Is there any way we could pass some regex to the path='*' of the router such that it excludes the routes from the parent project and render nothing if the path is included in parentprojectRoutes array?
Solution 1:[1]
You can write like:
<Route path="/:pth*">
// note that you need to pass the props to children
and use the parameter from props.match.params.pth.
Or you can define several routes with multiple regex paths. For instance
// this will match with urls starting with a and any numbers
<Route path="/:pth(a[0-9]*)">
// this will match with urls starting with z and any numbers
<Route path="/:pth(b[0-9]*)">
// then put the all matching Route
<Route path="*">
Note that in new version of react-router-dom@6 path order is not important it just matches with the best path.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kingofsevens |
