0
votes

I using react-router-dom v6. But when i want navigate its going to loop. I just want if url isnt one of that routes just navigate to "foo" url. In v5 version i can do it easily with redirect. But in v6 havent redirect so i must use navigate. But its making loop. My code :

const Login = React.lazy(() => import("./login"));
export const AppViews = () => {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Routes>
        <Route path={`${AUTH_PREFIX_PATH}/login`} element={<Login />} />
        <Route
          path="*"
          element={<Navigate to={`${AUTH_PREFIX_PATH}/login`} replace />}
        />
      </Routes>
    </Suspense>
  );
};

export default AppViews;

What is wrong in that code i really cant figure out. When path is /auth/login shouldn't it open element Login basicly? Its going loop when i make like this. Thank you for replies!

2
I copy/pasted your code into a codesandbox and it seems to work without issue. <Route path="*" element={<Navigate to={.....} replace />} /> is the v6 equivalent of the v5 Redirect component, it should works the same for the most part.Drew Reese
@DrewReese I tried upload to sandbox too but It didnt install dependencies i dont know why. So i sharing github link for you can check my codes. github.com/ugurcanucar/login-page.git Can you check it please? I really struggle a lot with new react-router-dom.Ugurcan Ucar

2 Answers

0
votes

Try this approach this works

const Login = React.lazy(() => import("./login"));
import {useNavigate} from "react-router-dom";

export const AppViews = () => {
  const navigate = useNavigate();
  
  const Navigator = () =>{
   navigate(`${AUTH_PREFIX_PATH}/login`)
  }

  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Routes>
      <Route path={`${AUTH_PREFIX_PATH}/login`} element={<Login />} />
      <Route
        path="*"
        element={<Navigator/>}
      />
    </Routes>
  </Suspense>
  );
};

export default AppViews;
-1
votes

Instead of using Navigate you can use the useNavigate hook, as shown below just import useNavigate hook in your app and collect it in navigate variable

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();

Then use it as shown below:

        <Route
          path="*"
          element={navigate(`${AUTH_PREFIX_PATH}/login`)}
       />

I hope it solved you issue.