Reputation: 995
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
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
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
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