skip to Main Content

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


  1. 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;
    
    Login or Signup to reply.
  2. 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:

    <React.StrictMode>
        <RouterProvider router={router}>
          <Link to="/">Home</Link>
          <Link to="/about">About</Link>
          <Outlet />
        </RouterProvider>
      </React.StrictMode>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search