While building web applications, we may find that some routes need to be hidden from anonymous users. I have found this need arise more often recently, and find that using a Higher Order Component for those routes work pretty well for my use-cases.
<PrivateRoute path="/dashboard" component={Dashboard} />
Example
Below is an example of how the <PrivateRoute />
HOC could look.
In a nutshell, <PrivateRoute />
takes another Component and passes it to <Route />
. If the user is not anonymous, the desired, private component is rendered by <Route />
. If not, the user is redirected to the login page.
<PrivateRoute />
can then be placed right alongside other public <Route />
components inside <BrowserRouter />
Final Thoughts
I wonder if there’s a way to group all public and private routes separately in order to only have to check if the user is not anonymous once, at a “private routes” entry point…