I have a custom reusable component library with a component that uses the useLocation hook to listen for changes in the route. The component library is packaged using rollup and published to an internal registry.
When installing this external library and using the component inside of a CRA project which implements react-router-dom v6 I get:
Error: useLocation() may be used only in the context of a component
This is despite it being inside a Router? It appears it is listening to a different context?
Is it possible to share components that use the router context?
UPDATE:
The package.json contains:
"dependencies": {
...
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3"
},
"peerDependencies": {
...
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3"
},
and the component itself looks like:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const MyCustomComponent = () => {
const location = useLocation();
useEffect(() => {
// do something here
}, [location]);
return <>Show Something Here</>;
}
In the consuming application (App.tsx):
<Router>
<MyCustomComponent />
<Routes>
...
</Routes>
</Router>
UPDATE:
The parent application had:
"react-router-dom": "^6.3.0"
Should having the peerDependency "react-router-dom": "^6.4.3" have fixed this or do consumers of the component library have to manually ensure the versions are aligned?
I fixed this issue by linking the node_modules/react-router-dom to shared lib. Here is the code snippet from my package.json. I hope it works for you as well.
{
"start": "npm run link && react-app-rewired start",
"link": "cd ../shared-lib && npm link && npm link ../user-panel/node_modules/react ../user-panel/node_modules/react-dom ../user-panel/node_modules/react-router-dom && cd ../user-panel && npm link shared-lib"
}
The problem is after bundling the javascript files shared lib still uses shared-lib/node_modules/react-router-dom so there are two instances for react-router-dom at the end.
By this way share-lib and user-panel use same instance of react-router-dom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With