Creating Private Route Component
In this lesson, we're going to create private route component
Creating private route component#
In almost every application, there are protected routes; which means routes that are reserved for some users with privileges. In our application, we don't want any anonymous user to visit the profile page. We can simply use redirect from React Router Dom or we can create a component which will make the private Route reusable. Let's work on the latter.
Inside components, let's create a new file called
PrivateRoute.tsx. Let's create a function called PrivateRoute and export it. Props for this component will extend RouteProps and we are expecting component as props which will be of type ComponentType of type RouteComponentProps of type Any, or ComponentType of type Any just to be safe. Let's destructure component and give it a type Component. It can take other props as well, so let's call it rest using spread operator.
Now, we want to check if the user exists, so let's write user from useAppSelector from state.user. We will return Route from this component. Let's write other rest props. Now we want to render the actual component if the user exists; otherwise, we want to use Redirect component to redirect the user to the login page. To make this work, we will use render, and take props as arguments. If the user exists, we want to render the component with props; otherwise, we will redirect the user to login page for which we will use pathname. Now we can simply go to the
App.tsx file and wrap the profile component with PrivateRoute instead of Route.