Ref error in React.JS Ref - createRef, useRef, and using Refs

4.9k Views Asked by At

I am trying to use the ref property using React. I get a strange error in my browser, and I am not able to figure out what the problem is. Can anyone explain to me why I get this error:

Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.

when I have this code:

/**
* @jsx React.DOM
*/
(function(){
var react = require('react');


var App = react.createClass({

    render: function() {
        return (
            <h1 ref="myRef">This is a test</h1>
        );
    }

});

react.render(
    <App />,
    document.body
);
}());
2

There are 2 best solutions below

1
On BEST ANSWER

Your code is correct.

Working jsFiddle: http://jsfiddle.net/reactjs/69z2wepo/

var App = React.createClass({

    render: function() {
        return (
            <h1 ref="myRef">This is a test</h1>
        );
    }

});

React.render(
    <App />,
    document.body
);

According to the error message, you're placing a ref on an un-owned element, but in the code you provided the h1 is owned by the App. Is your code different from what you pasted above?

Note (from the docs):

In React, an owner is the component that sets the props of other components ... 
It's important to draw a distinction between the owner-ownee relationship and the parent-child relationship. 
1
On

This answer may help you visit, check out your code carefully to aim at these two questions, my error is caused by the latter one.
In my code, I've written require("React") require("React-dom"), actually it is require('react'), I modified my code, it worked. All the errors are caused by the two factors. Just check your code completely.