I am trying to use modal on my application but I want to separated into different classes as App.js and /components/modal. The problem I encountered is I couldn't pass the props properly. Here is my codes.
I imported modal.
import InfoModal from '../components/InfoModal';
I created state.
state = {modalVisible: false}
The visible function on press.
setModalVisible = (visible) => {
this.setState({ modalVisible: visible });
}
Calling component.
render() {
const { modalVisible } = this.state;
return (
<InfoModal visible= {modalVisible} />
<TouchableOpacity onPress={() => this.setModalVisible(true)} ><Text style={styles.infoButton}>Info</Text></TouchableOpacity>
)}
I didn't understand what prop should I set and how, to work it properly.
Since you have a render method, I assume your App.js is a Class component.
You can create a state on the constructor like that
class App extends React.Component {
constructor(props){
super(props);
this.state = {
modalVisible: false,
}
}
// rest of the class
}
Your function for changing the modal's visibility should be like that
setModalVisible = (visible) => {
this.setState({modalVisible: visible});
}
That's how you control the state on the App class.
And for your modal, you pass App.state.modalVisible
as a prop.
<InfoModal visible={this.state.modalVisible} />
When you use setState, all the components receiving that new value as a prop will properly update