score:0

you are trying to use usenavigate() inside the app's component that is not inside a browserrouter because the browserrouter is inside the app's component and not around.

score:0

as the error suggests, you are using a hook in a component that isn't inside the <browserrouter>.

a potential solution would be to build a protectedroute component

const protectedroute = ({ children }) => {
  if (! isuserloggedin()) {
    return <navigate to={app_routes.login} replace />;
  }

  return children;
};

and wrap your route around it:

       <route
          path="home"
          element={
            <protectedroute>
              <dashboard />
            </protectedroute>
          }
        />

good blog post here: https://www.robinwieruch.de/react-router-private-routes/

score:0

issue

the app component is rendering the router that provides the routing context that the usenavigate hook needs.

solution

move browserrouter higher in the reacttree so that it can provide a routing context to components below it. wrapping app component with a router is correct if you want to use any react-router-dom hooks in the app component.

import react from 'react';
import { browserrouter } from 'react-router-dom';
import reactdom from 'react-dom';
import './index.css';
import app from './app';

reactdom.render(
  <browserrouter>
    <app />
  </browserrouter>,
  document.getelementbyid('root')
);

...

import { routes, route, usenavigate } from "react-router-dom";

function app() {
  const navigate = usenavigate();
  return (
    <routes>
      <route
        path={app_routes.dashboard}
        element={isuserloggedin()
          ? <dashboard />
          : <>pp{navigate(app_routes.login)}</>
        }
      />
    </routes>
  );
}

additional question

what would be the best way to add a couple of authenticated routes?

see how to create a protected route


Related Query

More Query from same tag