Vince Gonzales
Vince Gonzales

Reputation: 995

React Native - How to call a function from a child component?

I'm trying to make a Timer component which should start when its start function is called from a parent component:

Timer:

class Timer extends Component {
   start = () => {
      //starts the timer here
   }
}

Parent:

class Parent extends Component {
   render () {
      <Timer /> // how do I call the start function from this parent component?
   }
}

Upvotes: 2

Views: 80

Answers (3)

user1278673
user1278673

Reputation:

So the following is really bad practice, typically if you found yourself in a situation where you need to pass from child to parent there's a larger issue.

Also this solution should not be used verbatim but rather give you a really good idea of how to pass a function back to the parent from the child

class Timer extends Component {
   componentDidMount() {
      this.props.setIt(this.start)
   }

   start = () => {
      //starts the timer here
   }
}

class Parent extends Component {

   setIt = (startTrigger) => {
     startTrigger() // You now have access to this function to do what you wish
   }

   render () {
      <Timer setStartTrigger={this.setIt} />
   }
}

Upvotes: 0

Tarik Chakur
Tarik Chakur

Reputation: 1737

You may call the child function from the parent by setting reference to the child.

//Child
class Timer extends Component {
    start = () => {
        //starts the timer here
    }
}

//Parent
class Parent extends Component {

    rende() {
        <Timer ref={ ( component ) => this.Timer = component }/>
    }

   someParentFunction() {
       this.Timer.start();
   }

}

Upvotes: 3

oma
oma

Reputation: 1894

You should trigger change a prop from <Timer> and then start the timer in the componentWillReceiveProps. Small example

class Parent extends Component {
    //set the state to this.state={runTimerStart: false}
    onParentAction = () => {   //call this onParentAction function when you want to start the timer
        this.setState({runTimerStart: true})
    }
    render () {
        <Timer runStart={this.state.runTimerStart}/> 
    }
}

And in <Timer>

componentWillReceiveProps(nextProps){
  if(nextProps.runTimerStart === true){
    //Perform some operation, call your start function
  }
}

Upvotes: 1

Related Questions