I have some Routes in my application in which I have common a header and a nav links.
Currently, I got a requirement where in few routes, I want to show just the header
only and not nav
links.
Take the following example, Suppose for /billing
route, I don't want to show the nav links for it.
How could I do toggling of hide/unhide link across different routes?
function App() {
return (
<>
<header>
<Logo />
<Search />
<ActionButtons />
</header>
<BrowserRouter>
<nav>
<Link exact to="/">
Home
</Link>
<Link exact to="/about">
About
</Link>
<Link exact to="/contact">
Contact us
</Link>
</nav>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
<Route path="/cafeteria">
<Cafeteria />
</Route>
<Route path="/billing">
<Billing />
</Route>
</Switch>
</BrowserRouter>
</>
);
}
CodePudding user response:
You could render the navbar into a route and specify all the routes you want it to match and render on.
Example:
function App() {
return (
<>
<header>
<Logo />
<Search />
<ActionButtons />
</header>
<BrowserRouter>
<nav>
<Route
exact
path={["/about", "/contact", "/cafeteria", "/"]}
>
<Link exact to="/">
Home
</Link>
<Link exact to="/about">
About
</Link>
<Link exact to="/contact">
Contact us
</Link>
</Route>
</nav>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
<Route path="/cafeteria">
<Cafeteria />
</Route>
<Route path="/billing">
<Billing />
</Route>
</Switch>
</BrowserRouter>
</>
);
}
If you've a large number of routes then it may be more practical to use routes you want to exclude the rendering.
Example:
function App() {
return (
<>
<header>
<Logo />
<Search />
<ActionButtons />
</header>
<BrowserRouter>
<nav>
<Route
render={({ location }) => {
return ["/billing"].some(path => location.pathname === path)
? null
: (
<>
<Link exact to="/">
Home
</Link>
<Link exact to="/about">
About
</Link>
<Link exact to="/contact">
Contact us
</Link>
</>
);
}}
/>
</nav>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
<Route path="/cafeteria">
<Cafeteria />
</Route>
<Route path="/billing">
<Billing />
</Route>
</Switch>
</BrowserRouter>
</>
);
}