Recently, have you ever found yourself in an intriguing situation while working with the new version of react-router-dom
? I just encountered this situation, and I found myself thinking:
How the hell do I create private routes now? π§
So I decided to investigate and try the traditional authentication method, but to my surprise, this wasn't working as expected π.
function PrivateRoute ({ isPrivate, ...props }: Props) {
const { authenticated, loading } = useContext(AuthContext);
if(loading) {
return <Loading />;
}
if (isPrivate && !authenticated) {
return <Navigate to="/" />;
}
return <Route {...props} />;
}
However, to my surprise, Iβve found a way to create private routes in react-router-dom and I came today to share it with you. So, prepare yourself, because what comes next is pure React magic! β¨
First Step
As is customary, we will create our pagination structure using react-router-dom
inside the ./src/routes/index.routes.tsx
folder of our project. Following that, weβll export it to App.tsx
as usual.
/* File: index.routes.tsx */
import { Navigate, Route, Routes } from "react-router-dom";
import { Home } from "../pages/Home";
import { SignIn } from "../pages/SignIn";
import { SignUp } from "../pages/SignUp";
export function Router() {
return (
<Routes>
<Route element={<Home />} path="/" />
<Route element={<SignIn />} path="/sign-in" />
<Route element={<SignUp />} path="/sign-up" />
<Route element={<Navigate to="/" />} path="*" />
</Routes>
);
}
/* File: App.tsx */
import { BrowserRouter } from "react-router-dom";
import { Router } from "./routes/index.routes";
export default function App() {
return (
<BrowserRouter>
<Router />
</BrowserRouter>
);
}
Second Step
Within the routes file, we will create a function called PrivateRoutes()
. This function will be responsible for rendering specific components based on user authentication.
If the user is authenticated, our website will display the initial page (Home
) within the component <Outlet />
. On the other hand, if the user isn't authenticated, the <Navigate />
component with its to=β/sign-inβ
property will automatically redirect the user to the sign-in page.
/* File: index.routes.tsx */
import { Navigate, Route, Routes, Outlet } from "react-router-dom";
import { Home } from "../pages/Home";
import { SignIn } from "../pages/SignIn";
import { SignUp } from "../pages/SignUp";
function PrivateRoutes(){
const isUserAuth = true;
return isUserAuth ? <Outlet /> : <Navigate to="/sign-in"/>
}
export function Router() {
return (
<Routes>
<Route element={<SignIn />} path="/sign-in" />
<Route element={<SignUp />} path="/sign-up" />
<Route element={<PrivateRoutes />}>
<Route element={<Home />} path="/" />
<Route />
<Route element={<Navigate to="/sign-in" />} path="*" />
</Routes>
);
}
Done! From this point on, you can already have private pages in your project! I hope you enjoyed it.
Follow me for more tips π₯
Top comments (0)