Reputation: 495
New to React native and looking for a tip on how to do this best.
I have a screen component containing a modal component, and the modal contains a Contacts component with a checkbox list of Contacts. Upon hitting a button in the modal, I want to update the state of the screen component.
<Modal animationType="slide"
transparent={false}
visible={this.state.contactModalVisible}
onRequestClose={()=> {
this.setState({ contactModalVisible: false});
}}>
<ContactList // On pressAButtonInsideHere, how do I update the Screen state? />
</Modal>
Should I put the button inside the Modal component and have the ContactList component update the Modal component first? Or can I update the screen straight from ContactList?
Upvotes: 1
Views: 75
Reputation: 30390
It's valid to update screen state from a nested component (ie something inside of your <ContactList />
component). There are a number of approaches to this, and the most suitable approach will depend on your requirements. A simple way to do this however would be to add a callback to <ContactList />
.
So for instance, you could add the following onButtonPress
callback:
<Modal
animationType="slide"
transparent={false}
visible={this.state.contactModalVisible}
onRequestClose={() => {
this.setState({ contactModalVisible: false});
}}>
<ContactList onButtonPress={ () => this.setState({ yourChange : true }) }
// On pressAButtonInsideHere, how do I update the Screen state?
/>
</Modal>
And then update your <ContactList />
component to fire the onButtonPress
callback when an (internal) button component is pressed. To illustrate the general idea, consider this mock for <ContactList />
:
import { Button } from 'react-native'
const ContactList = () => {
return (<Button onPress={ () => this.props.onButtonPress() }
title="Button in contact list" />)
}
Upvotes: 1