Trying to create a plain router with default history object, but its throwing this error -
Module not found: Error: Can't resolve 'history/createBrowserHistory'
In the App.js file -
import history from './history'
const App = () => {
return (
<div className="ui container" style={{marginTop: '50px'}}>
<Router history={history}>
<Header />
<Routes>
<Route path="/" exact element={<StreamList />} />
</Routes>
</Router>
</div>
);
};
In the history.js file -
import createHistory from 'history/createBrowserHistory'
export default createHistory();
I also tried the solution mentioned in Module not found: Error: Can't resolve 'history/createBrowserHistory', but now its not rendering the App component at all, and getting the following error in console
Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') at Router
What could be the reason? I installed a separate history dependency, but its still not working.
CodePudding user response:
About issue:
Module not found: Error: Can't resolve 'history/createBrowserHistory'
I think issue is in a name of history module. There is not a module with a name 'history/createBrowserHistory'. Try that instead:
//history.js
import {createBrowserHistory} from 'history'
export default createBrowserHistory()
About issue:
Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') at Router
If you use react-router 6 then Router component does not have history in its props. You may try something like that:
<Router location={history.location} navigator={history}>
But, I would recommend to follow that advice - https://reactrouter.com/en/main/routers/router
CodePudding user response:
It seems you've incorrectly imported the createBrowserHistory
utility function. The named createBrowserHistory
export should be imported.
history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
With the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') at Router
I suspect you've not imported the correct router component. All the high-level routers (BrowserRouter
, HashRouter
, etc..) all instantiate and maintain an internal history
reference, and the low-level Router
has a few required props, none of which are history
. Import and use the HistoryRouter and provide your custom history object as a prop.
app.js
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from './history';
const App = () => {
return (
<div className="ui container" style={{ marginTop: '50px' }}>
<HistoryRouter history={history}>
<Header />
<Routes>
<Route path="/" element={<StreamList />} />
</Routes>
</HistoryRouter>
</div>
);
};