Search code examples
javascriptreactjswebpackbundling-and-minificationnpm-install

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


I have written a self-contained component and it works properly If I am running this component as a stand-alone component. I'd like to release this component as NPM module so I can share this component. In my sample application I've defined the path to the module in my package.json and it's being pulled down by NPM fine. I am using webpack for bundling and it successfully builds the package but when I run the code in the browser I get

Uncaught 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

I had spent a full day and tried few hacks but I am not able to found the exact root cause of the issue?


Solution

  • In your webpack config use this in the external configuration like:

    output: {
        path: __dirname + "/dist",
        filename: 'bundle.js',
        // library: 'hello-007',
        libraryTarget: 'umd',
      },
      externals: [{
        'react': {
          root: 'React',
          commonjs2: 'react',
          commonjs: 'react',
          amd: 'react'
        }
      }, {
        'react-dom': {
          root: 'ReactDOM',
          commonjs2: 'react-dom',
          commonjs: 'react-dom',
          amd: 'react-dom'
        }
      }],   
       module : {
        loaders : [
          {
            test : /\.js?/,
            loader : 'babel'
          }
        ]
      },