I have a React-based web application that utilizes React Router to map pages to different URLs:
export const Container = () => (
<div>
<SideNav/>
<div>
<Switch>
<Route path="/login" ponent={LoginView} />
<Route path="/route1" ponent={RouteOne} />
<Route path="/route2" ponent={RouteTwo} />
</Switch>
</div>
</div>
)
When any route gets hit, the sidebar gets rendered as well as the appropriate view. However, I am trying to build the layout such that for certain routes (such as "login"), the SideNav
doesn't get rendered and the ponent (in this case, LoginView
) is the only thing that gets rendered. In other words, LoginView
should take over the div
and be the only child of the top div
.
Is there anyway this can be done?
I have a React-based web application that utilizes React Router to map pages to different URLs:
export const Container = () => (
<div>
<SideNav/>
<div>
<Switch>
<Route path="/login" ponent={LoginView} />
<Route path="/route1" ponent={RouteOne} />
<Route path="/route2" ponent={RouteTwo} />
</Switch>
</div>
</div>
)
When any route gets hit, the sidebar gets rendered as well as the appropriate view. However, I am trying to build the layout such that for certain routes (such as "login"), the SideNav
doesn't get rendered and the ponent (in this case, LoginView
) is the only thing that gets rendered. In other words, LoginView
should take over the div
and be the only child of the top div
.
Is there anyway this can be done?
Share Improve this question asked Nov 5, 2017 at 22:48 DemCodeLinesDemCodeLines 1,9208 gold badges43 silver badges62 bronze badges 1- You can read up on this demo: reacttraining./react-router/web/example/sidebar, which allows you to have dynamic sidebar on different route – AngYC Commented Nov 5, 2017 at 22:56
2 Answers
Reset to default 6According to react-router docs:
path: string Any valid URL path that path-to-regexp understands.
path-to-regexp understand a string, array of strings, or a regular expression.
Array of routes:
State which routes will render the SideNav
as well (Working Example):
<Route path={['/route1', '/route2']} ponent={SideNav} />
RegExp:
Another option is to show the SideNav
only if the path doesn't contain a certain word (working example):
<Route path={/^(?!.*login).*$/} ponent={SideNav} />
And in your code:
export const Container = () => (
<div>
<Route path={['/route1', '/route2']} ponent={SideNav} />
<div>
<Switch>
<Route path="/login" ponent={LoginView} />
<Route path="/route1" ponent={RouteOne} />
<Route path="/route2" ponent={RouteTwo} />
</Switch>
</div>
</div>
)
Another approach (I am not sure about this but I faced the same problem and this is how I fixed it, but I admit it's less cleaner than what Ori Drori proposed):
In your SideNav ponent :
import React from "react";
import {useLocation} from "react-router"
export const SideNav = (props) => {
const location = useLocation();
const show = !location.pathname.includes("login");
return (
<>
{show && (<YourLoginComponentCode /> }
</>
)
}