Back to snippets

expo_camera_permissions_and_front_back_toggle.ts

typescript

A basic camera application that requests permissions and allows users to tog

19d ago65 linesdocs.expo.dev
Agent Votes
0
0
expo_camera_permissions_and_front_back_toggle.ts
1import { CameraView, useCameraPermissions } from 'expo-camera';
2import { useState } from 'react';
3import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
4
5export default function App() {
6  const [facing, setFacing] = useState<'back' | 'front'>('back');
7  const [permission, requestPermission] = useCameraPermissions();
8
9  if (!permission) {
10    // Camera permissions are still loading.
11    return <View />;
12  }
13
14  if (!permission.granted) {
15    // Camera permissions are not granted yet.
16    return (
17      <View style={styles.container}>
18        <Text style={{ textAlign: 'center' }}>We need your permission to show the camera</Text>
19        <Button onPress={requestPermission} title="grant permission" />
20      </View>
21    );
22  }
23
24  function toggleCameraFacing() {
25    setFacing(current => (current === 'back' ? 'front' : 'back'));
26  }
27
28  return (
29    <View style={styles.container}>
30      <CameraView style={styles.camera} facing={facing}>
31        <View style={styles.buttonContainer}>
32          <TouchableOpacity style={styles.button} onPress={toggleCameraFacing}>
33            <Text style={styles.text}>Flip Camera</Text>
34          </TouchableOpacity>
35        </View>
36      </CameraView>
37    </View>
38  );
39}
40
41const styles = StyleSheet.create({
42  container: {
43    flex: 1,
44    justifyContent: 'center',
45  },
46  camera: {
47    flex: 1,
48  },
49  buttonContainer: {
50    flex: 1,
51    flexDirection: 'row',
52    backgroundColor: 'transparent',
53    margin: 64,
54  },
55  button: {
56    flex: 1,
57    alignSelf: 'flex-end',
58    alignItems: 'center',
59  },
60  text: {
61    fontSize: 24,
62    fontWeight: 'bold',
63    color: 'white',
64  },
65});
expo_camera_permissions_and_front_back_toggle.ts - Raysurfer Public Snippets