I developed a simple admin dashboard and I use latest version of React router dom. I have a sidebar with some links. But when I use <Link>
component of React router dom I got error and the app crashes. All routes is in a file called router.jsx, my sidebar and the App which has <RouterProvider />
. Can you help me to solve this error.
Routes.js:
import { createBrowserRouter } from "react-router-dom";
import Dashboard from "./Pages/Dashboard/Dashboard";
import Users from "./Pages/Users/Users";
import ProductsList from "./Pages/Products/ProductsList";
import Orders from "./Pages/Orders/Orders";
import Reviews from "./Pages/Reviews/Reviews";
const Routes = createBrowserRouter([
{
path: "/",
element: <Dashboard />,
},
{
path: "/users",
element: <Users />,
},
{
path: "/products",
element: <ProductsList />,
},
{
path: "/orders",
element: <Orders />,
},
{
path: "/reviews",
element: <Reviews />,
},
]);
export default Routes;
App.jsx:
import { RouterProvider } from "react-router-dom";
import Sidebar from "./Components/Sidebar/Sidebar";
import Routes from "./Routes";
import NavBar from "./Components/Nav Bar/NavBar";
import FooterCopyRight from "./Components/Footer/FooterCopyRight";
function App() {
return (
<div className="lg:grid lg:grid-cols-12 bg-gray-100 min-h-screen">
<div className="bg-white p-5 col-span-2 hidden lg:flex border-x-2 shadow">
<Sidebar />
</div>
<div className="p-5 col-span-10 bg-gray-100 min-h-screen">
<NavBar />
<RouterProvider router={Routes} />
<FooterCopyRight />
</div>
</div>
);
}
export default App;
And I use Link Component like this:
<li className={liStyles}>
<Link to="/">Dashboard</Link>
</li>
I just wanted to have a separate file for all routes.
2
Answers
There’s an issue with how you’re using the createBrowserRouter function from react-router-dom in your Routes.js file. You should use BrowserRouter. The Routes component is just a functional component that returns a set of Route components, and you can use BrowserRouter directly in your App.jsx file.
Routes.js
App.jsx
You can use children on the root url like:
then create the Base component :
and finally update App component: