How to restrict access to routes in React Router?

Sometimes, we want to restrict access to routes in React Router.

In this article, we’ll look at how to restrict access to routes in React Router.

How to restrict access to routes in React Router?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we’re checking.

For instance, we write

import { Route, Redirect } from "react-router";

<Route
  exact
  path="/"
  render={() => (loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />)}
/>;

to render Redirect if loggedIn is true.

Otherwise, we render PublicHomePage.

Conclusion

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we’re checking.