skip to Main Content

I am using an asterisk (*) path in React Router to catch all undefined paths and redirect them to the home page for private routes, and to the login page for public routes. The redirection works correctly for login, but for private routes, although it redirects to the home page, the browser URL does not update correctly.



`  element: <PrivateRoutes />,
      children: [
        { path: appFileText.homeRoute, element: <Home /> },
        { path: appFileText.profileRoute, element: <Profile /> },
        { path: appFileText.aboutRoute, element: <About /> },
        { path: appFileText.restApiRoute, element: <RestApis /> },
        { path: appFileText.logoutRoute, element: <LogOut /> },
        { path: "*", element: <Home /> },
      ],
    },
    {
      element: <PublicRoute />,

      children: [
        { path: "*", element: <Login /> },
        { path: appFileText.loginText, element: <Login /> },
        {
          path: appFileText.counterRoute, element: <Counter initialCount={0} />,
        },
      ],
    },
  ]);`
 

Both functions should work the same way, and for private routes, the browser’s address bar should update. Additionally, navigating to any other link should return the user to the home page.

2

Answers


  1. since all undefined paths you are directing to page, you are just changing the component. you are not changing the url to show the component.
    Try creating a new component. use useNavigate or redirect from ‘react-router-dom’

    useEffect(() => redirect(appFileText.homeRoute),[]);
    //or
    const navigate = useNavigate();
    useEffect(() => navigate(appFileText.homeRoute),[]);
    
    Login or Signup to reply.
  2. Set const isAuthenticated = false in privateRoutes to simulate an unauthenticated state. This will allow you to test the redirect to ‘/login’ for private routes and the browser’s address bar will update correctly.

    import { Outlet, Navigate } from "react-router-dom";
    
    const PrivateRoutes = () => {
      const isAuthenticated = false; // Set this to false for testing
      return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
    };
    export default PrivateRoutes;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search