bazi
bazi

Reputation: 1866

React: get component in props.children

How can i call the rendered Child component's method from the Parent? Basically my application uses a switch statement to render 3 tabs each containing a MyComponent element at the root. I tried accessing using props.children but when i call the child method, it throws an error.

/* parent */

changeChild(component) {
    this.setState({component});
}

callChildMethod() {
    this.state.component.childMethod();
}

render() {
    return <Child tab={1} changeChild={this.changeChild} />
}    
/* child */

componentDidMount() {
    this.props.changeChild(this.refs.root.props.children) // pass to parent here
}

renderContent() {
    switch(this.props.tab) {
        case 0:
            return (
                <MyComponent />
            );
        case 1:
            return (
                <MyComponent />
            );
        case 2:
            return (
                <MyComponent />
            );
    }
}

render() {
    return (
         <div ref="root">
             {this.renderContent()}
         </div>
    )
}

Upvotes: 0

Views: 1959

Answers (1)

bogdan
bogdan

Reputation: 134

I would suggest a different approach. Don't save a referece to the child in state, just ask for the reference when you need to. And also by using a function as a ref it is less buggy.

Do you need to call navigator.pop() on <MyComponent /> or on the div with ref root? In the folowing example you can access eather the div or the component.

// parent

render() {
  return <Child ref={(ref) => this.childNode = ref} />
}

someMethod() {
  // make sure the component is mounted and you have a referece to child
  if (this.childNode) {
    // get child root node
    const childRootNode = this.childNode.getRootNode()
    // or get the comp node
    const compNode = this.childNode.getCompNode()
  }
}


/* child */
renderContent(setCompRef) {
    switch(this.props.tab) {
        case 0:
            return (
                <MyComponent ref={setCompRef} />
            );
        case 1:
            return (
                <MyComponent2 ref={setCompRef} />
            );
        case 2:
            return (
                <MyComponent3 ref={setCompRef} />
            );
    }
}

render() {
    return (
        <div ref={ref => this.rootNode = ref}>
            {this.renderContent(
              ref => this.compNode = ref // function that sets ref for component
            )}
        </div>
    )
}

// getters for the two refs
getRootNode() {
  return this.rootNode
}
getCompNode() {
  return this.compNode
}

Upvotes: 2

Related Questions