This post will be concentrating on writing private and public kind of route in a React application. We will be using react-router-dom to create the routes here. react-router-dom is a modern package applied to make routes. It uses react-router in its core. So without additional ado, lets dive into writing the routes.
What are we making here:
We are creating simplistic routes such that when a user attempts to have access to a specific page that they don’t have access to, they are redirected to the ones that they have access to. To place it in panorama, let’s have an example.
For the sake of integrity, we’ll just create three components here. They are:
- Home:- A public route that everyone can have access to.
- Sign-In:- A public route that verified users cannot have access to.
- Landing page:- A private that only verified users can have access to.
When a user is not logged in, they cannot reach the Landing page and when they attempt to access it, they are redirected to the Sign-In page. And furthermore, when a user is logged in, they shouldn’t have entrance to the Sign-In page.
Defining Private Routes
We are importing ‘loggedIn’ which returns us a Boolean value of whether the user is logged in or not. We set the private route by executing logic that if the user is logged in, display the component contrarily redirect to the Sign-In page. This means we have a reusable component for Private Route.
Defining Public Routes
Likewise, we set our public routes by having a conditional rendering on ‘loggedIn’ and ‘restricted’ flag. If they are logged in but the requested page is limited then redirect to Landing page otherwise display the component.
We import <BrowserRouter> and <Switch> from ‘react-router-dom’ and in our App.js file, we list our routes such as:
Now, we have successfully represented our public and private routes. While there may be many various ways to perform private and public routes, I found this one simple to understand and straightforward. We can certainly use our own logic to further better the way routes are managed. Go give it a try.