How Prevent Multiple Copies Of React from Loading?
Solution 1
Since you use webpack, you can add an alias for loading react, like this:
// In webpack.config.js
resolve: {
alias: {
react: path.resolve('node_modules/react'),
},
},
This prevented the addComponentAsRefTo(...)
error and made our build succeed again. However, for some reason, the testing build failed only on our CI environment as it could not resolve the node_modules/react
path. I think it's unlikely that you will encounter this particular problem, though.
Solution 2
In my case, I was building a separate npm module, then including that as a library in another project locally using npm link ../some-library
. One of the modules within that library caused this error when I ran the parent project.
When I ran into this error, the solution for me was to prevent react and react-dom from being including in the some-library bundle output, by adding the following to the module.exports of its webpack.config.js:
externals: {
react: 'react',
'react-dom': 'react-dom'
}
Solution 3
Something that worked for me was:
Uninstall all globally installed packages related to react (create-react-app, react-native, react and so on)
then: rm -rf node_modules
then: use npm install
instead of yarn install
considering an App created with crate-react-app and ejected
Solution 4
If You use web pack then you can fix it by adding the following to Webpack config for Don't bundle react or react-dom
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
}
Sylar
Updated on May 04, 2020Comments
-
Sylar about 4 years
In my previous Meteor app, using browserify, and React, all was working until I switched to meteor webpack.
I use react-select in my Meteor apps and it worked great but with browserify I could prevent multiple copies of react from loading which prevents this error I'm now having:
Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).
My package.json look this:
... "dependencies": { "classnames": "^2.1.3", "lodash": "^3.10.0", "react": "^0.14.6", "react-dom": "^0.14.6", "react-mixin": "^2.0.1", "react-select": "^1.0.0-beta8" }, ...
Is there a configuration in webpack I could use something call externals? Not fully sure what that means but a comment said to use:
externals: { 'react': 'React', 'react-dom': 'ReactDOM' }