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.
1 Answer
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 BrowserRouter source code as the example for how the high-level routers instantiate their history context.
Example:
const history = createBrowserHistory();
function App() { const [state, setState] = useState({ action: history.action, location: history.location }); useLayoutEffect(() => history.listen(setState), [history]); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <Router location={state.location} navigationType={state.action} navigator={history} > <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/pricing">Pricing</Link> </li> </ul> <Routes> <Route path="/" element={<h1>Home</h1>} /> <Route path="/about" element={<h1>About</h1>} /> <Route path="/pricing" element={<h1>Pricing</h1>} /> </Routes> </Router> </div> );
} 0