Mark As Completed Discussion

Protected Routes with React Router

In many web applications, there are certain routes that should be accessible only to authenticated or authorized users. React Router provides a way to create protected routes that require authentication or authorization before allowing access to certain pages or components.

To create a protected route in React Router, we can make use of the Route, Redirect, and render props. Here's an example of how we can implement a protected route:

SNIPPET
1const isAuthenticated = true;
2
3const ProtectedRoute = ({ component: Component, ...rest }) => {
4  return (
5    <Route
6      {...rest}
7      render={(props) => {
8        return isAuthenticated ? (
9          <Component {...props} />
10        ) : (
11          <Redirect to="/login" />
12        );
13      }}
14    />
15  );
16};

In this example, we create a ProtectedRoute component that accepts a component prop and other props using the spread operator (...rest). Within the render prop of Route, we check if the user is authenticated. If the user is authenticated, we render the provided component. Otherwise, we redirect the user to the login page using Redirect component.

By using the ProtectedRoute component in our application's routing configuration, we can easily protect certain routes that should only be accessible to authenticated users.

It's important to note that the isAuthenticated variable in this example is hardcoded for demonstration purposes. In a real-world application, you would typically use a state management solution or an authentication service to handle the authentication status.

In summary, React Router allows us to create protected routes by utilizing the Route, Redirect, and render props. By implementing protected routes, we can control access to certain pages or components based on authentication or authorization requirements.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment