Categories
React Answers

How to implement authenticated routes in React Router 4?

Spread the love

Sometimes, we want to implement authenticated routes in React Router 4.

In this article, we’ll look at how to implement authenticated routes in React Router 4.

How to implement authenticated routes in React Router 4?

To implement authenticated routes in React Router 4, we can create a component that checks the auth status and render the content according to that.

We can wrap this component around our authenticated routes so that they only show when the user is logged in.

For instance, we write

RouteRequiresLogin.js

import React from "react";
import { Route } from "react-router-dom";

const RouteRequiresLogin = props => {
   const userIsLogged = useLoginStatus();

   return (
      <Route {...props}>{userIsLogged ? props.children : <LoginPage/>}</Route>
   );
};

export default RouteRequiresLogin;

to create the RouteRequiresLogin component that renders props.children is the user is authenticated which we check with userIsLogged .

If userIsLogged is false, we render the LoginPage component.

Then we can use it by writing

<>
  <RouteRequiresLogin path="/dashboard">
    <DashboardPage />
  </RouteRequiresLogin>
  <Route path="/sign-up">
    <SignUpPage />
  </Route>
</>;

to wrap the DashboardPage, which requires authentication, with RouteRequiresLogin.

The public SignUpPage route wraps around the React Router Route component.

Conclusion

To implement authenticated routes in React Router 4, we can create a component that checks the auth status and render the content according to that.

We can wrap this component around our authenticated routes so that they only show when the user is logged in.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *