user1518183 user1518183 - 2 months ago 17
Javascript Question

React.js - access to component methods

Why I can't access the component methods from "outside" in React.js? Why it's not possible and is there any way to solve it?

Consider the code:

var Parent = React.createClass({
render: function() {
var child = <Child />;
return (
<div>
{child.someMethod()} // expect "bar", got a "not a function" error.
</div>
);
}
});

var Child = React.createClass({
render: function() {
return (
<div>
foo
</div>
);
},
someMethod: function() {
return 'bar';
}
});

React.renderComponent(<Parent />, document.body);


Thank you.

Answer

React provides an interface for what you are trying to do via the ref attribute. Assign a component a ref callback, and it will be called with a reference to the component when it is rendered:

var Parent = React.createClass({
    componentDidMount: function() {
        console.log(this._child.someMethod()); // Prints 'bar'
    },
    render: function() {
        return (
            <div>
                <Child ref={(child) => { this._child = child; } />
            </div>
        );
    }
});

Update 2016-09-19: Changed example to use ref callback rather than string ref per guidance from the ref String attribute docs.