Home > Back-end >  How can I show Alert message without clicking a button in React Native app?
How can I show Alert message without clicking a button in React Native app?

Time:08-31

I want to show an alert message immediately when I visit a specific page in my react native app. There should not be any Alert button, Alert should appear automatically whenever I visit the page. Thanks for your support.

import React, { useEffect, useState } from "react";
import {View, Text, StyleSheet, Alert} from 'react-native'
import { Ionicons } from '@expo/vector-icons';

const AlertTest = ({ navigation }) =>{

 return (
  <View style={{
    backgroundColor: '#f1f1f1',justifyContent: 'center', alignItems: 'center',}}>
<Ionicons color="black" name="tv" size={100}/>
    <Text>Hello World </Text>
</View>

);}
export default AlertTest;

CodePudding user response:

import React, {useEffect} from "react";
import {View, Text, ToastAndroid} from "react-native";
import {Ionicons} from "@expo/vector-icons";

const AlertTest = ({navigation}) => {
  useEffect(() => {
    alert("Some Alert");
    // OR
    ToastAndroid.show("Some Alert Toast", ToastAndroid.SHORT);
  }, []);

  return (
    <View
      style={{
        backgroundColor: "#f1f1f1",
        justifyContent: "center",
        alignItems: "center",
      }}>
      <Ionicons color="black" name="tv" size={100} />
      <Text>Hello World </Text>
    </View>
  );
};

export default AlertTest;

CodePudding user response:

Please find the below code:

import React, { useEffect, useState } from "react";
import {View, Text, StyleSheet, Alert} from 'react-native'
import { Ionicons } from '@expo/vector-icons';

const AlertTest = ({ navigation }) =>{

useEffect(() => {
    Alert.alert('Your alert msg here!')
},[])

 return (
  <View style={{
    backgroundColor: '#f1f1f1',justifyContent: 'center', alignItems: 'center',}}>
<Ionicons color="black" name="tv" size={100}/>
    <Text>Hello World </Text>
</View>

);}
export default AlertTest;

useEffect with [ ] will render one time only on-screen load.

Hope it will help you!

  • Related