Now we want to guard the protected page from unrestricted user access.
We need to write a GuardedRoute which wraps a normal React-Router <Route>:
View raw
Now we can use the new component inside the App.js component.
<GuardedRoute path='/protected' component={Protected} auth {isAutheticated} />
Let me explain the code above:
First of all we create a new component wrapping a React-Router <Route>. Then we rename the component prop to Component because in JSX lowercase tag names are considered html tags so component names should always start uppercase. Inside the render of the <Router> component we check if the user is authenticated. If true, display the protected component. If false we redirect to Home.js.
Now we are finished with the implementation. Restart your application and test the different <Routes>. It should not be possible to reach the protected component if your are not logged in. If you try to reach the protected page the application redirects to the home page.
More
You can find the final code in my GitHub repo:
More
Credits
The article was influenced by the following works on a similar topic: