Categories
TypeScript Answers

How to rewrite the protected routes using TypeScript and React-Router 5?

Spread the love

Sometimes, we want to rewrite the protected routes using TypeScript and React-Router 5.

In this article, we’ll look at how to rewrite the protected routes using TypeScript and React-Router 5.

How to rewrite the protected routes using TypeScript and React-Router 5?

To rewrite the protected routes using TypeScript and React-Router 5, we can define our own prop type for our route component.

For instance, we write

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

type ProtectedRouteProps = {
  isAuthenticated: boolean;
  authenticationPath: string;
} & RouteProps;

export default function ProtectedRoute({
  isAuthenticated,
  authenticationPath,
  ...routeProps
}: ProtectedRouteProps) {
  if (isAuthenticated) {
    return <Route {...routeProps} />;
  } else {
    return <Redirect to={{ pathname: authenticationPath }} />;
  }
}

to define the ProtectedRouteProps type that has the prop properties that we defined.

And then we combine that with RouteProps by creating an intersection type with it with &.

Then ProtectedRouteProps should have the props from both types.

And then we can use the props without TypeScript compiler errors.

Conclusion

To rewrite the protected routes using TypeScript and React-Router 5, we can define our own prop type for our route component.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.