Reputation: 191
Is it possible via react router to handle multiple independent routes in a view?
Like having a component that gets rendered via /home
and opening in a modal another view via /contact
and the components rendered by /home
stays in the background?
I only managed so far having 1 "active" component. As soon as I open up my modal via /contact
the home component is gone.
Upvotes: 0
Views: 2187
Reputation: 5061
By default, react-router
renders all matched routes in the order you render them.
So, your desired behavior is default behavior:
<main>
<Route path="/" component={() => <h1>Home</h1>} />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</main>
On route "/1"
above code will render components on the first and second routes.
And in order to render only one matched route at a time we need to use Switch
component:
<main>
<Switch>
<Route path="/" component={() => <h1>Home</h1>} exact />
<Route path="/1" component={() => <h2>Page 1</h2>} />
<Route path="/2" component={() => <h2>Page 2</h2>} />
</Switch>
</main>
Now, on route "/1"
above code will render a component from second route only.
exact
is used to not match "/"
all of the time.
Here is the fully working example https://codesandbox.io/s/nnv800pxr4
Also, there is another way to achieve such behavior - nested routes. Just render something else beyond child routes and it will be rendered all the time any of child routes are matched:
// somewhere in routes
<Route path="/home" component={HomeComponent} />
// HomeComponent content
<div>
<h1>Some content<h1>
<h2>Rendered every time HomeComponent are rendered!</h2>
<Switch>
{/* some child routes */}
<Routes path="/contacts" component={ContactModal} />
{/* some child routes */}
</Switch>
</div>
Note, that currently react-router@4
lacks good nested routes API. IMO, in react-router@3
such things were much easier to achieve.
Upvotes: 2