Zolve
Zolve

Reputation: 524

Call React Component Method From Parent

Im new to react and i was wondering how i can call a child components method from the parent?

for example

var ChildClass = class Child {

  howDoICallThis () {
    console.log('Called!')
  }

  render () {
    return (<Text> Child Class </Text>)
  }
}

var ParentClass = class Parent {
  // how can i call child.howDoICallThis() ?
  render () {
    return (<ChildClass> </ChildClass>)
  }
}

Can someone explain clearly how i can do this?

Upvotes: 2

Views: 316

Answers (1)

user6826724
user6826724

Reputation:

This isn't really how things should be done in React. One very common way of approaching these situations is to define methods within a container component that handles business logic, then pass those methods down to presentational components as props.

class Child extends Component {
    render () {
        return <Text onClick={this.props.handleClick}>Child Class</Text>
    }   
}

class Parent extends Component {
    handleClick = () => {
        console.log('Called!')
    }

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

Basically, you're wanting to pass things up, where React is designed to pass things down. You can still pass things up using refs and 'lifting state up' (see https://facebook.github.io/react/docs/lifting-state-up.html), but as far as methods go, you should really only ever pass them down. If you structure your components correctly, you shouldn't ever have to call a child's method from the parent.

(btw... make sure you are extending Component. you missed this in you sample code)

Upvotes: 1

Related Questions