I am developing a website in React with a login interface. The website displays a custom Navigation component, however I don't want it to display on the home route (i.e. the login page), but from what I understand, static components don't re-render on route changes, is that accurate?
I am using React-Router to handle all routing.
Here is what my App.js looks like now:
render() {
return (
<Router className="App">
<Header />
<NavigationBar />
<div id="container">
<Route path="/" exact component={LoginPage}/>
<Route path="/EventInfo" component={EventInfo}/>
<Route path="/RSVP" component={RSVP}/>
<Route path="/Attendance" component={Attendance}/>
<Route path="/Confirmation" component={Confirmation}/>
<Route path="/Contact" component={Contact}/>
<Route path="/Lodging" component={Lodging}/>
</div>
</Router>
);
};
That's correct. As currently constructed, your <NavigationBar />
would display at all times. What you can do is isolate the Routes
that use NavigationBar to their own component.
So try something like:
import { Switch, Router, Route } from "react-router-dom"; // fixed "
render() {
const AuthenticatedRoutes = () => {
return (
<NavigationBar />
<div id="container">
<Switch>
<Route path="/EventInfo" component={EventInfo}/>
<Route path="/RSVP" component={RSVP}/>
<Route path="/Attendance" component={Attendance}/>
<Route path="/Confirmation" component={Confirmation}/>
<Route path="/Contact" component={Contact}/>
<Route path="/Lodging" component={Lodging}/>
</Switch>
</div>
)
}
return (
<Router className="App">
<Header />
<Switch>
<Route path="/" exact component={LoginPage}/>
<Route component={AuthenticatedRoutes}/>
</Switch>
</Router>
);
};
In our new Router
definition, the Header
component will be displayed at all times.
The important thing here is to understand the Switch
component. It will render the first Route
whose path matches the URL provided. So if the URL is "/"
we will display only the Header
and LoginPage
.
But, let's say now we navigate to the URL "/EventInfo"
. Now, no path was matched in the outer Switch
defined in our Router
, so we render the AuthenticatedRoutes
component. The same pattern is executed, now we display NavigationBar
at all times and react-router-dom
will execute the inner Switch
to find a Route
whose path matches the URL provided. Thus rendering the EventInfo
component as well.
This structure is very useful for toggling the display of authenticated
and unauthenticated
components.
in NavigationBar.js you can do like this
import React, { useState } from "react";
import { useLocation } from "react-router-dom";
function NavigationBar() {
const location = useLocation();
const path = location.pathname;
const [display, setDisplay] = useState(
path !== "/" ? true : false
);
return (
<>
{display && (
<div>
</div>
)}
</>
);
}
export default NavigationBar;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With