I am trying to nest a path within another path in react-router-dom
version 6 and whenever I try to visit the nested argument's page (/blog/1
), it displays a blank non-styles HTML page but when I put a child path to the root ex. /blog
it renders perfectly fine.
Example router layout with nested argument:
import React from "React";
import { BrowserRouter, Routes, Route } from "react-router-dom"
import Main from "./pages/Main.tsx";
import ChatGPT from "./pages/ChatGPT.tsx";
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route index element={<Main />} />
<Route path="blog">
<Route path=":id" element={<Blog />} />
</Route>
</Routes>
</BrowserRouter>
);
};
Main.tsx:
import React from "react";
const Main = () => {
return (
<div>
<p>Home page</p>
</div>
);
};
export default Main;
Blog.tsx
import React from "react";
import { useParams } from "react-router-dom";
const Blog = () => {
const params = useParams();
const id = params.id;
return (
<div>
<p>Blog ID: {id}</p>
</div>
);
};
export default Blog;
I tried to put the <Outlet />
tag into the root of my component's <div>
tag that didn't work & I was expecting the react to render the nested argument's page correctly. I am also using Webpack's dev server to view the pages.
React: v18.2.0 | React Router DOM: v6.6.2 | Webpack: v5.75.0 | Webpack-cli: v5.0.1 | Webpack-dev-server: 4.11.1
CodePudding user response:
Main
and Blog
are default exports, which means they are default imports. Calling Main.default
or Blog.default
is likely returning undefined. Just Render <Main />
and <Blog />
.
import React from "React";
import { BrowserRouter, Routes, Route } from "react-router-dom"
import Main from "./pages/Main";
import Blog from "./pages/Blog";
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route index element={<Main />} />
<Route path="blog">
<Route path=":id" element={<Blog />} />
</Route>
</Routes>
</BrowserRouter>
);
};
CodePudding user response:
first of all, remove default from Main.default
and Blog.default