Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use react-router-dom Link component with the new router RouterProvider properly?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, just display 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.

>Solution :

You shouldn’t use link inside RouterProvider use it in any component.

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <RouterProvider router={router}/>
  </React.StrictMode>
);

In Home you can create link

import React from "react";
import { Link } from "react-router-dom";

const Home = () => {
  return (
    <div>
    <h1>Home</h1>
    <Link to="/about">About</Link>
    </div>
  )
}

export default Home;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading