I'm building a simple frontend application, and I'm using React Router V4, I'm trying to hide the navbar on the Login
and Register
screens.
Here is my App.js
code
class App extends Component {
constructor() {
super();
this.state = {
isNavbarHidden: false
};
}
componentDidMount() {
const currentRoutes = this.props.location;
if (currentRoutes === "/") {
this.setState({ isNavbarHidden: true });
}
} // end of componentDidMount
render() {
const { isNavbarHidden } = this.state;
console.log(isNavbarHidden);
return (
<div>
{!isNavbarHidden && <Navigation />}
<div className="sans-serif">
<Route exact path="/" component={Login} />
<Route exact path="/Register" component={Register} />
<Route exact path="/Home" component={Home} />
<Route exact path="/Dashboard" component={Dashboard} />
</div>
</div>
);
}
}
export default App;
and I have this in index.js
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
I thought when I did the if statement in componentDidMount
that would have fixed the issue, however on route '/'
the navbar is still shown
Any help would be appreciated!
I think instead of const currentRoutes = this.props.location;
you want something like const currentRoute = this.props.location.pathname
.
this.props.location
is an Object, so your condition will never be true
.
componentDidMount
will only be called once when your App
component is mounted.
You could listen to changes in the history
in componentDidMount
instead, and change isNavbarHidden
if the pathname
is /
or /Register
.
Example
class App extends Component {
constructor(props) {
super(props);
const { pathname } = this.props.location;
this.state = {
isNavbarHidden: pathname === "/" || pathname === "/Register"
};
}
componentDidMount() {
this.unlisten = this.props.history.listen(location => {
const { pathname } = location;
const isNavbarHidden = pathname === "/" || pathname === "/Register";
this.setState({ isNavbarHidden });
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
const { isNavbarHidden } = this.state;
return (
<div>
{!isNavbarHidden && <Navigation />}
<Link to="/">Login</Link>
<Link to="/Register">Register</Link>
<Link to="/Home">Home</Link>
<Link to="/Dashboard">Dashboard</Link>
<div className="sans-serif">
<Route exact path="/" component={Login} />
<Route exact path="/Register" component={Register} />
<Route exact path="/Home" component={Home} />
<Route exact path="/Dashboard" component={Dashboard} />
</div>
</div>
);
}
}
ReactDOM.render(
<BrowserRouter>
<Route path="/" component={App} />
</BrowserRouter>,
document.getElementById("root")
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.