ReactJS - Accessing Methods of Children (without using refs)

- 1 answer


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:

   <Child ref="testChild" />

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.


// Child.jsx

  customMethod() {},
  render() {... some stuff ...}

// Parent.jsx

   callChildrenMethods() {>{
           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.




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 - 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;