Categories
TypeScript Answers

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

Spread the love

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

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

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

To rewrite the protected routes using TypeScript and React-Router 6, we can define the type for the route props ourselves.

For instance, we write

export type ProtectedRouteProps = {
  isAuthenticated: boolean;
  authenticationPath: string;
  outlet: JSX.Element;
};

export default function ProtectedRoute({
  isAuthenticated,
  authenticationPath,
  outlet,
}: ProtectedRouteProps) {
  if (isAuthenticated) {
    return outlet;
  } else {
    return <Navigate to={{ pathname: authenticationPath }} />;
  }
}

to define the ProtectedRouteProps with some properties for the ProtectedRoute component props.

Then we can destructure the props and use them in the component.

We render outlet, which has the route component if isAuthenticated is true.

Next, we can use ProtectedRoute by writing

const App = () => {
  //...
  const defaultProtectedRouteProps: Omit<ProtectedRouteProps, "outlet"> = {
    isAuthenticated: !!sessionContext.isAuthenticated,
    authenticationPath: "/login",
  };

  return (
    <div>
      <Routes>
        <Route path="/" element={<Homepage />} />
        <Route
          path="dashboard"
          element={
            <ProtectedRoute
              {...defaultProtectedRouteProps}
              outlet={<Dashboard />}
            />
          }
        />
        <Route
          path="nested"
          element={
            <ProtectedRoute
              {...defaultProtectedRouteProps}
              outlet={<Layout />}
            />
          }
        >
          <Route path="one" element={<Protected />} />
          <Route path="two" element={<Protected />} />
        </Route>
        <Route path="login" element={<Login />} />
      </Routes>
    </div>
  );
};

to add the protected routes with the ProtectedRoute component by setting them as values for the Route component’s element prop.

Conclusion

To rewrite the protected routes using TypeScript and React-Router 6, we can define the type for the route props ourselves.

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 *