import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Button, Image, StyleSheet } from 'react-native';
import { Camera } from 'expo-camera';
export default function CameraCaptureScreen() {
const [hasPermission, setHasPermission] = useState(null);
const [photoUri, setPhotoUri] = useState(null);
const cameraRef = useRef(null);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const takePhoto = async () => {
if (cameraRef.current) {
const photo = await cameraRef.current.takePictureAsync();
setPhotoUri(photo.uri);
}
};
if (hasPermission === null) {
return <Text>Requesting camera permission...</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera. Please allow camera permission.</Text>;
}
return (
<View style={styles.container}>
<Camera style={styles.camera} ref={cameraRef} />
<Button title="Take Photo" onPress={takePhoto} />
{photoUri && <Image source={{ uri: photoUri }} style={styles.photo} />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 10
},
camera: {
width: '100%',
height: 300
},
photo: {
width: 300,
height: 300,
marginTop: 10
}
});This solution uses the Expo Camera module to show a live camera preview. When the screen loads, it asks the user for camera permission. If permission is granted, the camera preview is shown. A button labeled 'Take Photo' lets the user capture a picture. The picture's URI is saved in state and displayed below the button as an image. If permission is denied or still loading, a friendly message is shown instead.
We use a ref to access the camera methods. The takePictureAsync() method captures the photo. The UI updates automatically to show the captured image. This app is simple and shows how to use Expo modules to access device features easily.