Home > Mobile >  Router does not work with Link (React Router Dom 6)
Router does not work with Link (React Router Dom 6)

Time:04-14

So I have tested this on a fresh raw CRA 5 (typescript) app. In the App.tsx I just replaced it's contents to this:

import { Router, Routes, Route, Link } from "react-router-dom";
import "./App.css";

interface IProps {
  appHistory: any;
}

function App(props: IProps) {
  const { appHistory } = props;

  return (
    <div className="App">
      <Router location={appHistory.location} navigator={appHistory}>
        <ul>
          <li>
            <Link to="/">
              <strong>Home</strong>
            </Link>
          </li>
          <li>
            <Link to="/about">
              <strong>About</strong>
            </Link>
          </li>
          <li>
            <Link to="/pricing">
              <strong>Pricing</strong>
            </Link>
          </li>
        </ul>

        <Routes>
          <Route path="/" element={<div>Home Page</div>}></Route>
          <Route path="/about" element={<div>About Page</div>}></Route>
          <Route path="/pricing" element={<div>Pricing Page</div>}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

And the index.tsx to this:

import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserHistory } from "history";
import "./index.css";
import App from "./App";

const appHistory = createBrowserHistory();
const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(
  <React.StrictMode>
    <App appHistory={appHistory} />
  </React.StrictMode>
);

This doesn't seem to work. The routing does not work. Regardless of what you click it stays at home page. No console error logs.

I want to use the Router component explicitly for app design requirements. (Trying out Micro Frontend architecture).

Anyone knows what am I missing here?

Appreciate any help! Thanks in advance!

Lib versions:

"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"typescript": "^4.6.3",
"history": "^5.3.0"

Notes

  • Yes I am aware out BrowserHistory and yes it works fine.
  • I have tested this with and without history@5 lib and still it doesn't work
  • Remove that test file on CRA coz it causes issues on my code above.

CodePudding user response:

Move const appHistory = createBrowserHistory() out of the component. You want a stable history reference.

You'll need to implement some history state as well. Use the Edit router-does-not-work-with-link-react-router-dom-6

  • Related