Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v6 `useRouter` Hook with `basename` and Redirection

The following code snippet explains how I define the application routes.

let routes = useRoutes([
    { path: '/', element: <Home /> },
    {
      path: 'users',
      element: <Users />,
      children: [
        { path: '/', element: <UsersIndex /> },
        { path: ':id', element: <UserProfile /> },
        { path: 'me', element: <OwnUserProfile /> },
      ]
    }
  ]);

I would like to have a basename defined for all available routes. So, every route needs to have /ui/ basename prepended. '/' should also be redirected to '/ui/'.

Previously, during the beta phase it was possible to define basename as following:

  const routes = useRoutes(appRoutes, { basename: 'ui' });

However, it is no longer working.

like image 760
Burak Özdemir Avatar asked Sep 19 '25 11:09

Burak Özdemir


1 Answers

It looks like the current API is still pretty similar.

useRoutes

Type declaration

declare function useRoutes(
  routes: RouteObject[],
  location?: Partial<Location> | string;
): React.ReactElement | null;

It still takes a string base location, but now instead of being a "configuration" object it's directly a Location or a string.

For reference, here's the Location type declaration:

interface Location<S extends State = State> {
  pathname: string;
  search: string;
  hash: string;
  state: S;
  key: string;
}

So it seems you can either use a location partial and specify the pathname property, or a string.

const routes = useRoutes(appRoutes, { pathname: 'ui' });
const routes = useRoutes(appRoutes, 'ui');
like image 118
Drew Reese Avatar answered Sep 21 '25 03:09

Drew Reese