0

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.

nogabemist
  • 402
  • 5
  • 29

2 Answers2

0

use state and method inside Modal component and toggle it by using modal reference.

Put

const { modalVisible } = this.state;

and

setModalVisible = (visible) => {
        
        this.setState({ modalVisible: visible });
    }

in InfoModal.js

then use it like this

   render() {
    return ( 
        <InfoModal ref={(c)= this.infoModal=c }visible= {modalVisible} />  
        <TouchableOpacity onPress={() => this.infoModal.setModalVisible(true)} ><Text style={styles.infoButton}>Info</Text></TouchableOpacity>
)
Xhirazi
  • 735
  • 4
  • 15
0

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

Tramonta
  • 127
  • 5