Categories
React Answers

How to restrict access to routes in React Router?

Spread the love

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.

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 *