Skip to content

Instantly share code, notes, and snippets.

@mentix02
Created December 2, 2020 00:32
Show Gist options
  • Save mentix02/58e492df9390f326461ca0f526f2ed8a to your computer and use it in GitHub Desktop.
Save mentix02/58e492df9390f326461ca0f526f2ed8a to your computer and use it in GitHub Desktop.
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { useAuthenticated } from "../store/auth/hooks";
function PrivateRoute({
children,
...rest
}: {
children: JSX.Element | JSX.Element[];
}) {
const isAuthenticated = useAuthenticated();
return (
<Route
{...rest}
render={({ location }) =>
isAuthenticated ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location, error: "Please sign in first." },
}}
/>
)
}
/>
);
}
export default PrivateRoute;
import { Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Account from "./pages/Account";
import PrivateRoute from "./components/PrivateRoute";
const BaseRouter = () => (
<Switch>
<Route component={Home} path="/" exact />
<Route component={Login} path="/login" />
<PrivateRoute>
<Route component={Account} path="/account" />
</PrivateRoute>
</Switch>
);
export default BaseRouter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment