2

I'm trying to build a private and public route in React, and I'm using the useRoutes hook. I didn't know how to do this, already exist an answer to this question on Stack Overflow. However, it was just a copy and paste of some code. I really want to really learn how I can afford this.

I tried using the other answer, but it didn't help me much. If anyone can assist, I would be extremely grateful. This is the code I wrote.

import Home from "../pages/home"
import Items from "../pages/itens"
import Login from "../pages/login"
import Printers from "../pages/printers"
import { AuthContext } from "../contexts"
import { useContext } from "react"
import { Navigate } from "react-router-dom"

function Routes() {

    const { sessionContextValue } = useContext(AuthContext)
    const { isAuth } = sessionContextValue

    const routes = [
        {
            path: '/',
            element: isAuth ? <Home /> : <Navigate to={'/login'} replace/>,
        },
        {
            path: '/printers',
            element: <Printers />
        },
        {
            path: '/items',
            element: <Items />
        },
        {
            path: '/login',
            element: <Login />
        }
    ]

    let router = useRoutes(routes)
    return router
}

export default Routes

1 Answers1

0

To create private and public routes with the useRoutes hook, you can use a custom component that checks the authentication status of the user and renders the appropriate element or redirects to the login page. For example, you could create a PrivateRoute component like this:

import { Navigate, useLocation } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../contexts";

export default function PrivateRoute({ element }) {
  const { sessionContextValue } = useContext(AuthContext);
  const { isAuth } = sessionContextValue;
  const location = useLocation();

  return isAuth ? (
    element
  ) : (
    <Navigate to="/login" state={{ from: location }} replace />
  );
}

Then, you can use this component in your routes array like this:

import Home from "../pages/home";
import Items from "../pages/items";
import Login from "../pages/login";
import Printers from "../pages/printers";
import { useRoutes } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";

function Routes() {
  const routes = [
    {
      path: "/",
      element: <PrivateRoute element={<Home />} />,
    },
    {
      path: "/printers",
      element: <PrivateRoute element={<Printers />} />,
    },
    {
      path: "/items",
      element: <PrivateRoute element={<Items />} />,
    },
    {
      path: "/login",
      element: <Login />,
    },
  ];

  let router = useRoutes(routes);
  return router;
}

export default Routes;
Pluto
  • 4,177
  • 1
  • 3
  • 25