Reputation: 406
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!
Upvotes: 1
Views: 4916
Reputation: 203552
From what I could see you had an issue with absolute linking. Converting to relative linking seems to resolve looping issue. Either approach should work, but without digging deeper into your configs here's what worked for me.
views/index.js - append the wildcard *
to the path so nested routes can be matched and rendered.
export const Views = (props) => {
const { token } = props;
return (
<>
<Routes>
<Route path={`${AUTH_PREFIX_PATH}/*`} element={<AuthLayout />} />
<Route
path="/*"
element={
<RouteInterceptor isAuthenticated={token} element={<AppLayout />} />
}
></Route>
</Routes>
</>
);
};
views/auth-views/index.js - Use relative routing, i.e. remove the AUTH_PREFIX_PATH
prefixing.
const Login = React.lazy(() => import("./login"));
export const AppViews = () => {
return (
<Suspense fallback={<p>Loading...</p>}>
<Routes>
<Route path={"login"} element={<Login />} />
<Route path="/*" element={<Navigate to="login" replace />} />
</Routes>
</Suspense>
);
};
Forked codesandbox from your github repo
Upvotes: 1
Reputation: 605
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;
Upvotes: 1