react-native

How to display toast message in react native


I am trying to display a toast message in react native on button click

import React,{ Component } from 'react';
import { StyleSheet,TextInput, View, Button, Text, ToastAndroid } from 'react-native';

export default class App extends Component {

  state = {
              placeName : "",
              titleText: "Text view"
          }

  placeNameChangeHandler = val =>{
   this.setState({
     placeName : val
   })
  }

  placeSubmitHandler = () =>{
    this.setState({
      titleText: this.state.placeName.trim() 

    })
  }

   render() {
      return (
      <View style={styles.rootContainer}>

        <View style={styles.btnEditContainer}>
          <View style ={styles.wrapStyle}>
          <TextInput
          style = {styles.textInputStyle}
          value = {this.state.placeName}
          onChangeText = {this.placeNameChangeHandler}
          />
        </View>
          <View style ={styles.wrapStyle}>
          <Button
          title="Add"
          style ={styles.buttonStyle}
          onPress ={this.placeSubmitHandler}/>
        </View>
        </View>

        <View style={styles.textContainer}>
          <View style ={styles.wrapStyle}>
            <Text
            style ={styles.textStyle}>
            {this.state.titleText}
            </Text>
          </View>
        </View>

        </View>
      );
   }
}

const styles = StyleSheet.create({
  rootContainer: {
    height:"100%",
    width:"100%",
    backgroundColor: "#008000",
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  btnEditContainer: {
    backgroundColor:"#008080",
    flexDirection:"row",
    alignItems:"center",
    justifyContent: "center"
  },
  textContainer: {
    backgroundColor:"#00FFFF",
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  textStyle: {
    fontSize: 20,
    flexDirection:"column",
    alignItems:"center",
    justifyContent: "center"
  },
  buttonStyle: {
  },
  textInputStyle: {
    borderColor:"black",
    borderWidth:1,
  },
  wrapStyle: { marginLeft:5,
    marginRight:5 },
});

Solution

  • Can use below notifyMessage to show toast message:

    import { ToastAndroid, Platform, AlertIOS} from 'react-native';
    
    function notifyMessage(msg: string) {
      if (Platform.OS === 'android') {
        ToastAndroid.show(msg, ToastAndroid.SHORT)
      } else {
        AlertIOS.alert(msg);
      }
    }
    

    OR

    Use react-native-simple-toast in both iOS & Android.

    import Toast from 'react-native-simple-toast';
    
    Toast.show('This is a toast.');
    Toast.show('This is a long toast.', Toast.LONG);