Home > Enterprise >  React Router 6: new useRoutes() method -> how to define a 'redirect'?
React Router 6: new useRoutes() method -> how to define a 'redirect'?

Time:12-17

Using the new React Router 6, I prefer using the Route Objects method (using useRoutes()) over the normal JSX route definitions.

I want to redirect from '/' to '/login'. The docs do not mention though how to achieve such a redirect. Below are my current routes. What am I missing here?

const routes = [
  { path: '/', element: <Login /> },
  { path: 'login', element: <Login /> },
  { path: 'test', element: <Test /> },
  { path: 'chat', element: <Chat /> },
  { path: '*', element: <NotFound /> },
];

CodePudding user response:

Add <Navigate to="/login" /> as element for / path.

const routes = [
  { path: '/', element: <Navigate to="/login" /> },
  { path: 'login', element: <Login /> },
  { path: 'test', element: <Test /> },
  { path: 'chat', element: <Chat /> },
  { path: '*', element: <NotFound /> },
];

Check this link. I have edited their official example and added a redirect from /login to /. You can navigate across links using links present in the lower half of the UI.

https://stackblitz.com/edit/github-xlvehj?file=src/App.tsx

  • Related