ReactJS - Accessing Methods of Children (without using refs)
I am trying to access the methods of a children in the parent Component.
First I wanted to use refs instead of this.props.children, but refs are only accessable when using them IN my component.
When using this, it seems not to be possible:
<Parent>
<Child ref="testChild" />
</Parent>
In my Parent Component I am not able to access this.refs.testChild
- because of this I have to access this component with this.props.children
.
However: When accessing them with this.props.children
I am not able to call methods of the child.
Example:
// Child.jsx
{
customMethod() {},
render() {... some stuff ...}
}
// Parent.jsx
{
callChildrenMethods() {
this.props.children.map((child)=>{
console.log(child.props); // Props Object
console.log(child.customMethod); // Undefined
});
},
render() {return(<div>{this.props.children}</div>)}
}
As you can see: The customMethod is undefined. Is there any simple way to access the methods ? The better way would be to access the children with refs
but this is not possible in my case.
Answer
this.props.children
is opaque, you should iterate using React.Children API. Anyways, here's a fiddle which uses some hackery to invoke the child methods -
https://jsfiddle.net/sukantgujar/4bffu7tw/3/
Basically you need to access the type object of the child which points to the wrapped component instance.
var child = React.Children.only(this.props.children),
childType = child.type,
childProto = child.type.prototype,
childName = childProto.constructor.displayName,
childMethod = childProto.someMethod;
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?