Search code examples
reactjsreact-componentreact-ref

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


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
);
}());

Solution

  • 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.