I have a monorepo with multiple apps & libraries in it which works really well (yarn based). I did some refactoring lately and identified a common component which I wanted to "outsource" in my 'commons' library. This contains a component that uses a ReactRouter.Route
:
import React from 'react';
import { Route, useHistory } from 'react-router-dom';
export const AuthenticatedRoute = (props: Props): JSX.Element => {
const history = useHistory(); // Crashes here
... do auth stuff ...
useEffect(() => {
if (!authenticated) {
history.push(...);
}
}, []);
return (
<Route {...props}>
{props.children}
</Route>
);
}
This component works like a charm when contained my react app. However, when extracted into the commons
library, it fails at runtime with the following error:
Uncaught TypeError: Cannot read property 'history' of undefined
at useHistory (index.js:5914)
at AuthenticatedRoute (index.js:9848)
at renderWithHooks (react-dom.development.js:16260)
at mountIndeterminateComponent (react-dom.development.js:18794)
at beginWork$1 (react-dom.development.js:20162)
at HTMLUnknownElement.callCallback (react-dom.development.js:336)
at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
at invokeGuardedCallback (react-dom.development.js:440)
at beginWork$$1 (react-dom.development.js:25780)
at performUnitOfWork (react-dom.development.js:24695)
I guess this is somehow related on how the library / app reference the react-router-dom
library.
commons/package.json:
{
"name": "commons",
"version": "1.0.0",
"main": "dist/index.js",
"private": true,
"dependencies": {
},
"peerDependencies": {
"react-router-dom": "^5.1.2"
}
}
app/package.json:
{
"name": "app",
"version": "1.0.0",
"private": true,
"dependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"commons": "1.0.0"
}
}
app/app.ts:
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
export const App = (): JSX.Element => {
return (
<Router>
<AuthenticatedRoute />
</Router>
);
};
Note: If I comment the useHistory
, it fails at the <Route>
saying it needs to be a child of a <Router>
which it is.
Things I tried:
- use
peerDependencies
so that the library & app use the same instance of react router - clean & yarn install multiple times
- wild combinations of
react-router
&react-router-dom
dependencies