Search code examples
react-nativereact-native-modal

react native: modal is not displaying


I am new to react-native and I am trying to display modal in react-native with following code

      <View>
    <View onPress={() => {this.toggleModal(true) }}  onBackdropPress={ () => 
   {this.hideModal(false)}}>

        <View>
            <OcticonsIcons name='plus' size={19}/>

            <Text>QUICK ACTION</Text>
        </View>

        <View>
            <View>
                <Image source={require('../images/truck.png')} 
                />
                <Image source={require('../images/taxi(1).png')} 
                />
                <Image source={require('../images/tour.png')} 
                />
            </View>
        </View>

     </View>

    </View>
    <Modal visible={this.state.isModalVisible} animationType = "slide" transparent = 
    {false}>
            <View style={{ flex: 1 }}>
             <Text style={{ fontWeight:'bold', fontSize: 20, color: '#f79334', marginTop: 15 
      }} > Services </Text>
            </View>
      </Modal>


  toggleModal(visible){
   this.setState({ isModalVisible: visible });
  }

    hideModal(visible){
   this.setState({ isModalVisible: visible })
   }

but it's not working, can anyone tell me what wrong with my code, thank you.


Solution

  • The thing is you cant have onPress function on components, its solely for just showing. To use onPress you have to use TouchableOpacity.

    Check the code below :

     <View>
        <TouchableOpacity onPress={() => {this.toggleModal(true) }}  onBackdropPress={ () => 
       {this.hideModal(false)}}>
    
            <View>
                <OcticonsIcons name='plus' size={19}/>
    
                <Text>QUICK ACTION</Text>
            </View>
    
            <View>
                <View>
                    <Image source={require('../images/truck.png')} 
                    />
                    <Image source={require('../images/taxi(1).png')} 
                    />
                    <Image source={require('../images/tour.png')} 
                    />
                </View>
            </View>
    
         </TouchableOpacity>
    
        </View>
        <Modal visible={this.state.isModalVisible} animationType = "slide" transparent = 
        {false}>
                <View style={{ flex: 1 }}>
                 <Text style={{ fontWeight:'bold', fontSize: 20, color: '#f79334', marginTop: 15 
          }} > Services </Text>
                </View>
          </Modal>
    
    
      toggleModal = (visible) =>{
       this.setState({ isModalVisible: visible });
      }
    
        hideModal = (visible) => {
       this.setState({ isModalVisible: visible })
       }
    

    Hope it helps. feel free for doubts