1import { StackNavigationProp } from '@react-navigation/stack'; 2import * as React from 'react'; 3import { Button, Platform, ScrollView, Text, View } from 'react-native'; 4import { 5 SafeAreaView, 6 useSafeAreaInsets, 7 SafeAreaInsetsContext, 8} from 'react-native-safe-area-context'; 9 10import HeadingText from '../components/HeadingText'; 11 12export default function SafeAreaContextScreen({ 13 navigation, 14}: { 15 navigation: StackNavigationProp<any>; 16}) { 17 React.useLayoutEffect(() => { 18 navigation.setOptions({ 19 title: 'Safe Area Context', 20 header: () => null, 21 }); 22 }, [navigation]); 23 24 const [focused, setFocused] = React.useState<'hook' | 'view'>('hook'); 25 const insets = useSafeAreaInsets(); 26 27 if (focused === 'hook') { 28 return ( 29 <SafeAreaInsetsContext.Consumer> 30 {(consumerInsets) => ( 31 <ScrollView 32 style={{ flex: 1 }} 33 contentContainerStyle={{ 34 paddingTop: insets.top, 35 paddingHorizontal: 16, 36 paddingVertical: 8, 37 }}> 38 <HeadingText>Using useSafeArea hook</HeadingText> 39 <Text style={{ marginVertical: 10 }}>{JSON.stringify(insets, null, 2)}</Text> 40 <HeadingText>Using SafeAreaConsumer component</HeadingText> 41 <Text style={{ marginVertical: 10 }}>{JSON.stringify(consumerInsets, null, 2)}</Text> 42 <Button title="Switch to SafeAreaView" onPress={() => setFocused('view')} /> 43 <View style={{ marginVertical: Platform.OS === 'ios' ? 0 : 10 }} /> 44 <Button title="Go back to APIs" onPress={() => navigation.goBack()} /> 45 </ScrollView> 46 )} 47 </SafeAreaInsetsContext.Consumer> 48 ); 49 } else { 50 return ( 51 <SafeAreaView style={{ alignItems: 'center' }}> 52 <HeadingText>Using SafeAreaView</HeadingText> 53 <Text style={{ marginVertical: 10, textAlign: 'center' }}> 54 If it works as expected then the above heading will not be obscured by a device notch or 55 status bar. 56 </Text> 57 <Button 58 title="Switch to SafeAreaConsumer & useSafeArea hook" 59 onPress={() => setFocused('hook')} 60 /> 61 <View style={{ marginVertical: Platform.OS === 'ios' ? 0 : 10 }} /> 62 <Button title="Go back to APIs" onPress={() => navigation.goBack()} /> 63 </SafeAreaView> 64 ); 65 } 66} 67