ReactJS - Accessing Methods of Children (without using refs)

- 1 answer

Ad

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.

Ad

Answer

Ad

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;
Ad
source: stackoverflow.com
Ad