Home > Mobile >  React Router Dom - React Router changing url but not page
React Router Dom - React Router changing url but not page

Time:05-16

I'm trying to make a simple routing system with react, but when i click on a link to navigate to another page it just changes the URL but not showing the content, then when i press F5 it shows anything fine.

Here's my code, i can't understand what i'm doing wrong, i tried also to create another app but the result is the same.

Index.js

import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

App.js

import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Dashboard from "./pages/Dashboard/Dashboard";
import Notes from "./pages/Notes/Notes";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" component={Dashboard} exact />
        <Route path="/notes" component={Notes} />
      </Switch>
    </Router>
  );
}

export default App;

Dashboard

import PageContent from "../../components/PageContent/PageContent";
import ResponsiveDrawer from "../../components/ResponsiveDrawer/ResponsiveDrawer";

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

const Dashboard = () => {
  return (
    <>
      <ResponsiveDrawer>
        <PageContent
          header={
            <div className={`flex-row`}>
              <h1
                className={`font-extrabold tracking-tight truncate capitalize`}
              >
                dashboard
              </h1>
            </div>
          }
          body={<>Bentornato utente!</>}
        ></PageContent>
      </ResponsiveDrawer>
    </>
  );
};

export default Dashboard;

CodePudding user response:

Using version 6.

  1. Import Routes instead of Switch and replace <Switch> in your code.

  2. Use element instead of component, and add the actual component as its value rather than just the name.

  3. You should probably move the Notes route first as I think the ordering has an effect.

<Router>
  <Routes>
    <Route path="/notes" element={<Notes />} />
    <Route path="/" element={<Dashboard />} exact />
  </Routes>
</Router>

  • Related