Reputation: 891
As described here, when using hooks in a react library, you often encounter a react error saying hooks can only be called inside the body of a function component
The most likely cause for this error is that your library links to its own react package and you main app also, so you end up using 2 different copies of the react package.
One typical solution to this error is to make sure you main app AND your library use the exact same react package.
The solution I use, is to:
myMainApp/node_modules/react
yarn link
myLib
yarn link react
This solution works. My main app and my library now use the same react package.
But what if I have multiple main apps? Let's say I have this project structure:
mainApp1 using lib1-1 and lib1-2
mainApp2 using lib2-1 and lib2-2
Both main apps are independent of each other. So lib1-1 and lib1-2 should link to the react package of mainApp1 and lib2-1 and lib2-2 should both link to the react package of mainApp2
How do I do that? When I try to run yarn link
in mainApp2/node_modules/react
, yarn tells me that there is already a link for react.
Unfortunately, I cannot use yarn link as react2
or something similar.
Any ideas on how to overcome this?
Note: this problem can be overcome by building your library (where react is a devDependency), committing your changes to git after every tweak and than upgrade the library in your main app. But off course, this is not a solution since during developing, you want to link to you libraries instead of re-importing them from the repo's
Upvotes: 4
Views: 6338
Reputation: 11
if you are using a custom Webpack then you have to mention to use react from your node_modules.
resolve: {
alias: {
react: path.resolve('./node_modules/react'),
},
}
Upvotes: 1
Reputation: 9887
You can install react and react-dom globally, then link all of your projects to the global instance.
The procedure would be similar to the one you're using already, but creating symlinks to the global locations:
yarn global add react
yarn global add react-dom
Then you can link to them from your individual projects.
Upvotes: 1