I want to restrict parts of my app to logged in users only. I have this working using the code below.
However, previously I was making use of the Switch router to send users to a 404 page when no matching routes are found.
For some reason since I adding the EnsureLoggedIn component to App.jsx the user is never redirected to the 404 page.
Test: Random path entered in URL. Should route to the 404 page.
- isLoggedIn=false : The user gets directed to the /login page.
- isLoggedIn=true : No matching route is found and the page container is rendered empty.
I'd expect the switch router to ignore what's nested inside EnsureLoggedIn since none of the routes match, then render the 404.
Hoping someone with a bit more React experience can steer me on this.
App.jsx
<BrowserRouter>
<Header/>
<Switch>
<Route exact path="/" component={HomePage}/>
<Route exact path="/someotherpage" component={SomeOtherPage}/>
<EnsureLoggedIn>
<Route exact path="/dashboard" component={Dashboard}/>
</EnsureLoggedIn>
<Route component={Error404Page}/>
</Switch>
<Footer/>
</BrowserRouter>
EnsureLoggedIn.jsx
class EnsureLoggedIn extends Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: false};
}
render() {
const isLoggedIn = this.state.isLoggedIn;
if (isLoggedIn) {
return this.props.children
} else {
return ( <Redirect to="/login" /> );
}
}
}