React Router Link and NavLink doesn't load the component

Hello,

I’m working on the react router v5. I don’t understand the component <Link>. I take this code from React-Router v5 and I don’t understand why it doesn’t work fine.
The problem, when I click on the link my component Home, or About, Dashboard is not loaded. Only the url is changed but not my component.

import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";


// You can think of these components as "pages"
// in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}


export default function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/dashboard">Dashboard</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/dashboard" component={Dashboard} />
        </Switch>
      </div>
    </Router>
  );
}

My dependencies

  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },

Ok I have found the problem. Be carefull of your versions.

Use React-router-dom V5 with React V16

OR use React-router-dom V6 with React V18

Thanks here StackOverflow

I don’t think that is true.

All the examples in the docs use React 18 and they suggest using create-react-app which again would put the user at React 18.

Also, the code you posted here works just fine for me, and so does the code you posted on StackOverflow, although that code is incomplete so it is hard to know why that might not be working for you.


Post a complete example on StackBlitz or CodeSandbox of the code that isn’t working for you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.