Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Alert.alert() only works on iOS and Android, not web

I just started learning and practicing React Native and I have run into the first problem that I can’t seem to solve by myself.

I have the following code, which is very simple, but the Alert.alert() does not work when I run it on the web. If I click the button nothing happens, however, when I click the button on an iOS or Android simulator, it works fine.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';

export default function App() {
  return (
      <View style={styles.container}>
        <Text style={styles.headerStyle} >Practice App</Text>
        <Text style={{padding: 10}}>Open up App.js to start working on your app!</Text>
        <Button
          onPress={() => alert('Hello, Nice To Meet You  :)')}
          title="Greet Me"
        />
        <StatusBar style="auto" />
      </View>
  );
}

I also know that alert() works on all three devices, however, I want to understand why Alert.alert() only works for iOS and Android.

My question is more so for understanding rather than finding a solution. Is the only solution to use alert(), or am I implementing Alert.alert() in the wrong way?

like image 415
Thepurplelounge.com Avatar asked Sep 11 '25 23:09

Thepurplelounge.com


1 Answers

This workaround basically imitates react-native's Alert behavior with browsers' window.confirm method:

# alert.js
import { Alert, Platform } from 'react-native'

const alertPolyfill = (title, description, options, extra) => {
    const result = window.confirm([title, description].filter(Boolean).join('\n'))

    if (result) {
        const confirmOption = options.find(({ style }) => style !== 'cancel')
        confirmOption && confirmOption.onPress()
    } else {
        const cancelOption = options.find(({ style }) => style === 'cancel')
        cancelOption && cancelOption.onPress()
    }
}

const alert = Platform.OS === 'web' ? alertPolyfill : Alert.alert

export default alert

Usage:

Before:

import { Alert } from 'react-native'
Alert.alert(...)

After:

import alert from './alert'
alert(...)

Source & Credits: https://github.com/necolas/react-native-web/issues/1026#issuecomment-679102691

like image 168
Mehmet Kaplan Avatar answered Sep 13 '25 14:09

Mehmet Kaplan