2
votes

I am having an issue with adding a ref to a react component. Below is the error message.

invariant.js:39Uncaught 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

Research shows to probable causes for this, and neither seem to be the issue.

Only a ReactOwner can have refs

This is the most likely cause do to my unfamiliarity with react. I have a container being rendered, and then a select element being rendered into the container.

Code

var React = require('react');

var first_container = React.createClass({
    render: function() {
        return (
            <div id='first-container' className='jumbotron'>
               <div className='row'>
                  <button type='button' className='btn btn-primary'>Submit Query</button>
               </div>
        </div>
         );
     }
});


var product_selections = React.createClass({
   handleChange: function() {
      console.log("hello");
   },
   componentDidMount: function (){
      $(this.refs['product-select']).select2({
         change: this.handleChange
      });
   },
     render: function() {
        return (
            <div className='row'>
               <br/>
               <label htmlFor='product-dropdown'>
                  Product
                  <br/>
                  <select ref='product-select' className='js-example-basic-multiple js-states form-control' id='product-dropdown' multiple='multiple'>
                  </select>
               </label>
            </div>
        );
    }
});

You are trying to add a ref to an element that is being created outside of a component's render() function.

The ref is defined inside the render function, so it doesn't seem that that is the issue. Could it be that it's because this component is being added to another component?

Multiple Copies of React

npm ls | grep react

├─┬ [email protected]
├── [email protected]
├── [email protected] extraneous
├── [email protected]
├─┬ [email protected]
│ ├─┬ [email protected]

There does not seem to be a duplicate package either? Any ideas on what could be happening here?

1

1 Answers

0
votes

I had a similar issue and was able to resolve it by not using string refs.

Good:

 <input ref={(input) => { this.textInput = input }} />

Bad:

 <input ref="textInput" />

Check out the docs here: https://facebook.github.io/react/docs/refs-and-the-dom.html

They actually say don't do that:

"If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead."