Reputation: 679
I have this components structure:
I need based on 2 different routes to load inside < OtherComponent> the corresponding route from Router.
I using: "react-router-dom": "^5.1.2"
, and saw some posts talking about using IndexRoute and props.children, but IndexRoute cann't be resolved from react-router-dom, seems it was removed in version 5.
My Router (BrowserRouter) looks like this:
<Router basename={process.env.REACT_APP_ROUTER_BASE || '/MyApp'}>
<Switch>
<Route path="/" exact component={HomePage} />
{/*<IndexRoute component={ProjectsList} /> // The component to send to HomePage's `props.children` when route is '/'*/}
<Route path="/login" component={Login} />
<Route path="/editProject" component={ProjectEditor} />
{/*<Redirect path="*" to="/" />*/}
</Switch>
</Router>
At the beginning < ProjectsList> is loaded inside < HomePage> (hardcoded),
but from ProjectsList there is a need to edit a project, so need to load the < ProjectEditor> this time inside < HomePage>
A more detailed structure:
Upvotes: 1
Views: 5348
Reputation: 12672
IndexRoute
was indeed removed from React-Router as of v4. It was used as some sort of "default route"
Routes are now regular components, and can be rendered as part of any component, as long as some top component has a Router definition. Nesting routes allows you to compose the routes and render components with that structure.
Routes also have a render function in which you can render any component
If you need to render ProjectsList
as children of HomePage, why don't you pass it as a children?
<Route path="/" exact render={() => <HomePage><ProjectsList /></HomePage>} />
Furthermore, if you're using the latest version of React Router (5.1.0), you can use the children
props for routes to render, rather than a render prop
<Route path="/" exact>
<HomePage><ProjectsList /></HomePage>
</Route>
Update
Given your update
At the beginning < ProjectsList> is loaded inside < HomePage> (hardcoded),
but from ProjectsList there is a need to edit a project, so need to load the < ProjectEditor> this time inside < HomePage>
you can define on your HomePage
component, inside your render, two routes
return (
<Switch>
<Route path="/editProject"><ProjectsList /></Route>
<Route path="/"><ProjectsList /></Route>
</Switch>
)
(Depending on the version, you might have to use render={() => ...}
instead
If for whatever reason, you prefer to have all routes within the same file, you could also do this inside your route definition.
<Route path="/" exact>
<HomePage>
<Switch>
<Route path="/editProject"><ProjectsList /></Route>
<Route path="/"><ProjectsList /></Route>
</Switch>
</HomePage>
</Route>
But in this case, you will have to render children
in your HomePage
component
Upvotes: 3