This content originally appeared on DEV Community and was authored by Med Amine Fh
If you're using react router in your App, then you probably wanted to protect some routes from specific users, or to Redirect some users to their own page or component.
so what to do ?
In this blog we'll see How to handle that with some simple checks
So at the beginning this is how our App looks like
At this point every user can access those two components (Admin, Home)
But that's not what i want, I want just the admin to have access to the "/admin
" route.
And those who don't have access to that route, I need to redirect them to the Home Page ("/
" route)
So the 1st Step is to create the ProtectedRoute Component.
You can create it in the same file, but for a cleaner code we'll create it on a new file
1- Create a file and name it to what you want. I'll name it protectedRoute.js
.
2- Paste this code in that file
So basically we check if there is a token stored in our LocalStorage or not.
If The check is Truthy then he Have access to that route.
If Not, He will be Redirected to the Home Page (thanks to the <Redirect />
Component).
You need to change that check to suit your case.
Don't forget to export your Component.
3- Finally we'll use that ProtectedRoute in our App
Import The ProtectedRoute Component from where you created it
you can name it what you want if you export it with the default
So here we need to changed The
<Route exact path="/admin" component={Admin} />
with
<ProtectedRoute exact path="/admin" component={Admin} />
And that's it ?, Go Try it out.
This content originally appeared on DEV Community and was authored by Med Amine Fh
Med Amine Fh | Sciencx (2021-09-28T18:09:26+00:00) Protect Your components with React Router. Retrieved from https://www.scien.cx/2021/09/28/protect-your-components-with-react-router/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.