0

I have a child component that renders a button. When this button is pressed, I would like to animate the button, while simultaneously updating the state of the parent component so that it shows a different view.

How can these both be done from the one event? I thought to call a single function/method, but I am unsure how to update the parents state from within a method - I only know how to do this on an event listener in the render method.

Heres the child -

return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.props.buttonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>              
        </View> 

    );
  }
}
David
  • 3
  • 2

2 Answers2

0

Pass a callback as a prop from the parent to the child (which it looks like you are doing already), but then wrap the call to it in a local event handler method to do anything else you need to do in the child as well, instead of referencing the callback directly in your onPress

Note the use of arrow function syntax in the onButtonClick method - this will mean you already have a lexically bound this to the scope of the class instance

SomeChild

onButtonClick = () => {
   // do whatever you need to get done in this child
   this.whatever()
   // call the parents callback to make it do whatever changes it needs 
   this.props.buttonClicked()
}

render () {
  return (
        <View>
             <View style={styles.switch}>
                 <TouchableHighlight onPress={this.onButtonClick}>
                    <Animated.View
                        style={{
                          marginLeft,
                          height: 30,
                          width: 40,
                          backgroundColor: 'red'}} />
                 </TouchableHighlight>
              </View>              
        </View> 

      );
    }
  }
}

Parent

onChildClickedCallbackMethod = () => {
  // do something with parent here...
}

render() {
   return <SomeChild buttonClicked={this.onChildClickedCallbackMethod} />
}
alechill
  • 4,274
  • 18
  • 23
0

You can pass a callback from parent to the child in the form of props to the child component.

On click of the button, you can first animate the button and once that is done, you can call the callback that is passed from parent to child.

Alternatively, you can first call the callback and then animate. This depends on your requirements and how does your code run.

How to update parent's state in React?

Harshil Lodhi
  • 7,274
  • 1
  • 33
  • 42