iOSDev
iOSDev

Reputation: 412

React-Native How to update parent state variable from child component

I am presenting a component using Modal in react-native. So in the Child component(the component that is presented on top of parent as Modal) I am trying to update the state variable of parent, but it is throwing error like "'changeModalVisibility' is missing in props validation".

Kindly help me to solve this.

Related Code is below:

// Parent Class in render
<SafeAreaView style={styles.container}>
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.isModalVisible}
          onRequestClose={() => { this.changeModalVisibility(false) }}
        >
          <ChildClass
            changeModalVisibility={this.changeModalVisibility}
          />
        </Modal>
</SafeAreaView>
// Outside Render function
changeModalVisibility = (bool) => {
 this.setState({ isModalVisible: visible });
}

// In Child Class 
<TouchableHighlight
              underlayColor="none"
              onPress={this.props.closeButtonTapped}
              style={{ alignItems: 'center', justifyContent: 'center', }}
            >
              <Text style={{
                color: 'white',
                marginTop: 10,
                marginLeft: 20,
                fontWeight: '600',
                fontSize: 18,
              }}
              >Close
              </Text>
            </TouchableHighlight>

closeButtonTapped() {
this.props.changeModalVisibility //"**'changeModalVisibility' is missing in props validation**"
}

Upvotes: 1

Views: 2509

Answers (1)

Matin Zadeh Dolatabad
Matin Zadeh Dolatabad

Reputation: 1017

Your Child component in parent component has changeModalVisibility prop.
You should call
this.props.changeModalVisibility(true) or this.props.changeModalVisibility(false)
inside child component. Make sure to use arrow function when you want to execute function from prop :

changeModalVisibility={this.changeModalVisibility}

changeModalVisibility = (visible) => {
 this.setState({ isModalVisible: visible });
}

In child component onPress props should be like this:

onPress={() => this.closeButtonTapped()}

Upvotes: 2

Related Questions