snippetjavascriptreactCritical
How to access component methods from “outside” in ReactJS?
Viewed 0 times
methodsaccessfromreactjshowcomponentoutside
Problem
Why can’t I access the component methods from “outside” in ReactJS? Why is it not possible and is there any way to solve it?
Consider the code:
Consider the code:
var Parent = React.createClass({
render: function() {
var child = ;
return (
{child.someMethod()} // expect "bar", got a "not a function" error.
);
}
});
var Child = React.createClass({
render: function() {
return (
foo
);
},
someMethod: function() {
return 'bar';
}
});
React.renderComponent(, document.body);Solution
React provides an interface for what you are trying to do via the
Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component
Update 2019-04-01: Changed example to use a class and
Update 2016-09-19: Changed example to use ref callback per guidance from the
ref attribute. Assign a component a ref, and its current attribute will be your custom component:class Parent extends React.Class {
constructor(props) {
this._child = React.createRef();
}
componentDidMount() {
console.log(this._child.current.someMethod()); // Prints 'bar'
}
render() {
return (
);
}
}
Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component
Update 2019-04-01: Changed example to use a class and
createRef per latest React docs.Update 2016-09-19: Changed example to use ref callback per guidance from the
ref String attribute docs.Context
Stack Overflow Q#24841855, score: 223
Revisions (0)
No revisions yet.