Every React app with a login has some version of a PrivateRoute. React Router v6 changes the building blocks that component was made of, so the old pattern doesnβt carry over as is. Letβs rebuild it for v6.
π Continue reading on my blog: π Private Route in React Router v6
Top comments (61)
Awesome man! Huge thanks π
ΰ€Άΰ€Ύΰ€¨ΰ€¦ΰ€Ύΰ€° ΰ€²ΰ₯ΰ€ ΰ€ΰ€Ύΰ€
Great
thanks
Awesome !
Perfeito, muito obrigado (thank you)! But just aesthetic issues I recommend I created the component that manages private routes receiving props and your code is more reduced and clean.
component={Page} should be capital C component or should at lease be defined:
I was using a module to route users to I only need to render the header once etc.. so in I have outlet to render the nested routes. How can I now use the with the nested routes. This was my homeModule
And this is how I would want to have it work:
Whoops, I already figured it out, this was the code for my privateoutlet:
Yes π I was about to write that you need to change PrivateOutlet
is it necesary write Outlet twice?
Nice πππ
How do you protect a set of routes using PrivateRoute?
Repeating ...
... is not very elegant.
Thank you!
You could use
auth-react-routerpackage npmjs.com/package/auth-react-routerIt provides a really simple API to define your routes and few more configurations (like redirect routes for authorized and unauthorized routes, fallback component for each of the routes)
Just define your routes path and pages component and it will work