I’m learning the latest version of React and React-Router-Dom, I create a simple demo app.
Home.jsx
import React from "react";
const Home = () => {
return (
<div>Home</div>
)
}
export default Home;
About.jsx
import React from "react";
const About = () => {
return (
<div>About</div>
)
}
export default About
index.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider, Link } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "/about",
element: <About />
}
]);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<RouterProvider router={router}>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</RouterProvider>
</React.StrictMode>
);
but it doesn’t display the link, it just displays the content in Home
or About
component. No errors in the console.
I have searched a lot and didn’t find what’s the problem of the above code.
2
Answers
You shouldn’t use link inside
RouterProvider
use it in any component.In Home you can create link
Please make sure to check your package.json file to ensure that you have successfully installed react, react-dom, and react-router-dom. If they are installed correctly, you can import ReactDOM like this: ‘import ReactDOM from "react-dom"’. If still it is not working, then importing Outlet from react-router-dom. You are not using an Outlet component to specify where the matched content should be rendered. In that case, you should wrap your Link tag in an Outlet component like this: