I am trying to set up my project for the first time using useRoutes and lazy loading with children. But I am having a problem that it won't load the children when redirected to that site? The Home page works perfectly fine.
https://codesandbox.io/s/great-rgb-ippuob?file=/src/Page/Home/index.js Home path="/"
import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
</>
);
};
export default Home;
Children:
import React from "react";
import { useParams } from "react-router-dom";
const Id = () => {
const { id: loadingId } = useParams();
return <h1>Right now you are on the side of: {loadingId}</h1>;
};
export default Id;
App.js:
import "./styles.css";
import Route from "./Routes";
import { Suspense } from "react";
export default function App() {
return (
<>
<div className="App">
<Suspense fallback={<p>Loading...</p>}>
<Route />
</Suspense>
</div>
</>
);
}
Routes:
import { useRoutes } from "react-router-dom";
import React from "react";
export default function Router() {
return useRoutes([
{
path: "/",
element: <Home />,
children: [{ path: "/:id", element: <Id /> }]
}
]);
}
const Home = React.lazy(() => import("./Page/Home"));
const Id = React.lazy(() => import("./Page/Id"));
And in Index I have
<BrowserRouter>
<App />
</BrowserRouter>
You should add <Outlet /> in Layout/Parent component (Home for you)
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
<Outlet />
</>
);
};
export default Home;