Home > Software engineering >  React Link element v5 not taking me to the desired page
React Link element v5 not taking me to the desired page

Time:04-15

I'm having trouble with this simple react routing. The problem is that after I click on "Go to invoices" or "Go to eshop", the URL changes, but the page content remains the same. It only changes if I am at localhost:1234/eshop (or /dashboard) and reload the page.

import { BrowserRouter as Router, Route, Link } from "react-router-dom";    
export default function App() {
  return (
    <Router>
      <h1>Default layout</h1>
      <Link to="/invoices">Go to invoices</Link>
      <Link to="/eshop">Go to eshop</Link>

      <Route path="/invoices">
        <h2>Invoices page</h2>
      </Route>
      <Route path="/eshop">
        <h2>eshop page</h2>
      </Route>
    </Router>
  );
}

Any ideas how to fix this? edit sandbox here https://codesandbox.io/s/hungry-cloud-i2hui2?file=/src/App.js

CodePudding user response:

It's a clash between React Router and StrictMode.

One possible solution is to place the Router outside of StricMode, in the index.js file itself:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <Router>
    <StrictMode>
      <App />
    </StrictMode>
  </Router>
);

See: here and here

CodePudding user response:

You should wrap your Route components with a Switch component.

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

export default function App() {
  return (
  <Router>
   <h1>Default layout</h1>
   <Link to="/invoices">Go to invoices</Link>
   <Link to="/eshop">Go to eshop</Link>
   <Switch>
    <Route path="/invoices">
      <h2>Invoices page</h2>
    </Route>
    <Route path="/eshop">
      <h2>eshop page</h2>
    </Route>
  </Switch>
 </Router>
 )
}

https://v5.reactrouter.com/web/guides/quick-start

  • Related