Protected Routes

React router doesn’t give us an out of the box way to handle protected routes, istead, we have to create our own <ProtectedRoute> composed component that will use the render prop instead of composition on it <Route> component and only render the component if the user is authed, otherwise it uses the <Redirect> component to redirect the user to login.

Another thing to comment on is that you may want to ‘remember’ where the user wanted to go before they got redirected to login to authenticate so that you can redirect them there once they login. You can do that with our already mentioned link props (state).

You can see an example of all this on the following sandbox:


Protected Routes - CodeSandbox

Protected Routes - CodeSandbox

Copyright 2023 © Borja Leiva

Made within London