Integrating Device Hardware (Expo SDK)
9 min read
Mobile phones are essentially supercomputers packed with physical sensors: lenses that capture light, GPS chips that ping satellites, and haptic motors that vibrate. A mobile application that does not use these features is basically just a website trapped in an app icon.
In this guide, we are going to learn how to break out of the digital screen and interact with the physical device using the Expo SDK.
1. Accessing the Camera: Taking Photos and Scanning Barcodes
The Problem
You want your user to capture a profile picture or scan a QR code. You cannot simply access the camera hardware directly because operating systems strictly sandbox applications to prevent unauthorized surveillance. You need a secure, optimized bridge between your React Native JavaScript code and the device's physical camera lens and image processing units.
The Solution
expo-camera solves this by providing a direct line to the native iOS and Android camera APIs. It gives you a <CameraView> component that safely renders the live hardware feed directly onto your app's UI, while handling complex tasks like autofocus, zoom, and real-time barcode detection under the hood.
Installation & Setup
Always grab the latest version from Expo's registry:
npx expo install expo-cameraNote: For bare React Native apps, you will need to add camera permissions in your app.json or native configuration files. Expo Go handles this out of the box.
Concept Breakdown
Before you can show the camera, you must ask for permission. Imagine you are visiting a high-security data center. You cannot just walk into the server room; you have to stop at the front desk and ask for a visitor badge. Mobile operating systems work exactly the same way. The user is the front desk, and your app must formally request the "Camera Badge" before it can see anything.
Here is the standard flow:
- Check if permission is granted.
- If not, ask the user.
- Once granted, render the
<CameraView>.
import { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { CameraView, useCameraPermissions } from 'expo-camera';
export default function CameraScreen() {
// 1. Hook into the OS permission system
const [permission, requestPermission] = useCameraPermissions();
const [scannedData, setScannedData] = useState(null);
if (!permission) {
// Camera permissions are still loading from the OS
return <View />;
}
if (!permission.granted) {
// 2. We don't have the badge yet, ask the user
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>We need your permission to show the camera</Text>
<Button onPress={requestPermission} title="Grant Permission" />
</View>
);
}
// 3. Permission granted! Show the live feed and listen for barcodes.
return (
<View style={styles.container}>
<CameraView
style={styles.camera}
facing="back"
onBarcodeScanned={({ data }) => {
setScannedData(data);
console.log("Barcode scanned: ", data);
}}
>
<View style={styles.overlay}>
{scannedData && <Text style={styles.text}>Scanned: {scannedData}</Text>}
</View>
</CameraView>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center' },
camera: { flex: 1 },
overlay: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', paddingBottom: 50 },
text: { fontSize: 24, fontWeight: 'bold', color: 'white', backgroundColor: 'rgba(0,0,0,0.5)', padding: 10 }
});Industry Standards & Usability
- Unmount when hidden: A live camera feed is incredibly resource-intensive. If a user navigates away from the camera screen to their profile page, and you leave the
<CameraView>rendering in the background, their phone will heat up and drain the battery. Always unmount the camera component when the screen loses focus (using React Navigation'suseIsFocusedhook, for example). - Handle denial gracefully: Users will deny your permission request out of reflex. Do not crash the app. Show a polite fallback UI explaining why the camera is necessary and providing a button to open the OS settings.
2. Expo Image Picker: Selecting Media from the Gallery
The Problem
Your users do not always want to take a brand new photo. Usually, they want to upload an existing image from their device's media library. Building a custom interface to read the device's internal file system, generate thumbnails, and display them in a grid is a massive engineering effort fraught with memory limits and privacy violations.
The Solution
expo-image-picker solves this by telling the OS to open its own built-in, highly optimized photo gallery. The user selects an image in an interface they are already familiar with, and the OS securely hands a temporary copy of that file back to your app.
Installation & Setup
npx expo install expo-image-pickerConcept Breakdown
Using the image picker is straightforward. You invoke a function, the OS takes over the screen, and when the user finishes, it returns a Promise containing the result.
import { useState } from 'react';
import { Button, Image, View, StyleSheet } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function ProfilePictureUploader() {
const [imageUri, setImageUri] = useState(null);
const pickImage = async () => {
// Open the OS gallery
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images, // Only allow images (no videos)
allowsEditing: true, // Let the user crop the image
aspect: [1, 1], // Force a square crop
quality: 0.5, // Compress the image!
});
if (!result.canceled) {
// The user didn't hit 'cancel', save the URI
setImageUri(result.assets[0].uri);
}
};
return (
<View style={styles.container}>
<Button title="Pick an image from gallery" onPress={pickImage} />
{imageUri && <Image source={{ uri: imageUri }} style={styles.image} />}
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', justifyContent: 'center' },
image: { width: 200, height: 200, borderRadius: 100, marginTop: 20 },
});Industry Standards & Usability
- Always Compress (
quality: 0.5): Modern smartphone cameras take raw photos that can easily exceed 10MB to 15MB. If you upload these raw images to your database, your AWS/server storage bill will skyrocket, and the upload will take forever on a bad 4G connection. Settingqualityto0.5or0.7visually looks identical on mobile screens but reduces the file size by 80%.
3. Expo Location: Fetching User Coordinates and Permissions
The Problem
You are building a delivery tracker, a weather app, or a dating app. You need to know the exact physical coordinates (latitude and longitude) of the device. Communicating directly with the physical GPS chip, cell tower triangulation APIs, and Wi-Fi positioning systems is a mathematical and platform-specific nightmare.
The Solution
expo-location acts as a unified wrapper around the iOS Core Location and Android Location Services. It handles the raw calculations and simply hands you a clean JavaScript object containing the coordinates, accuracy, and timestamp.
Installation & Setup
npx expo install expo-locationConcept Breakdown
Location relies on a strict permission hierarchy. You usually only need Foreground Permission, which means you only track the user while they are actively looking at the app.
import { useState, useEffect } from 'react';
import { Platform, Text, View, StyleSheet, Button } from 'react-native';
import * as Location from 'expo-location';
export default function MapScreen() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const fetchLocation = async () => {
// 1. Ask for permission to use location while the app is open
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied.');
return;
}
// 2. Fetch the actual GPS coordinates
let currentLocation = await Location.getCurrentPositionAsync({});
setLocation(currentLocation);
};
return (
<View style={styles.container}>
<Button title="Where am I?" onPress={fetchLocation} />
{errorMsg && <Text>{errorMsg}</Text>}
{location && (
<Text style={styles.text}>
Latitude: {location.coords.latitude} {"\n"}
Longitude: {location.coords.longitude}
</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', justifyContent: 'center' },
text: { marginTop: 20, fontSize: 18, textAlign: 'center' }
});Industry Standards & Usability
- Avoid Background Location Unless Absolutely Necessary: Polling the GPS sensor constantly while the app is closed will drain a user's battery so fast they might think their phone is melting. Furthermore, Apple and Google App Store reviewers will ruthlessly reject your app if you request Background Location permissions without a highly justified reason (like turn-by-turn driving navigation). Stick to Foreground permissions.
- Reverse Geocoding Limits: Expo Location can turn coordinates into readable addresses (e.g., "123 Main St") using
Location.reverseGeocodeAsync(). However, this relies on OS rate-limited network calls. Do not put this in a loop, or the OS will block your requests.
4. Device Haptics and Tactile Feedback
The Problem
Your user taps a crucial "Confirm Transfer" button. Visually, the button might change color, but the flat glass of the phone screen provides zero physical resistance. Without physical feedback, users often double-tap buttons or feel disconnected from the interface, wondering if their action actually registered.
The Solution
expo-haptics triggers the physical motors inside the device (the Taptic Engine on iOS, the Vibrator service on Android) to deliver precise, micro-vibrations to the user's hand. This tricks the brain into feeling a physical "click".
Installation & Setup
npx expo install expo-hapticsConcept Breakdown
Haptics are entirely synchronous to implement and do not require user permissions. There are three main types of feedback:
- Impact: Used to simulate physical collisions or weight (e.g., a modal snapping into place, a toggle switch).
- Notification: Used to convey the result of an action (e.g., a success checkmark, an error failure).
- Selection: Used to indicate a change in state across a continuous range (e.g., spinning a date picker wheel).
import { View, Button, StyleSheet } from 'react-native';
import * as Haptics from 'expo-haptics';
export default function FeedbackScreen() {
const handleSuccess = () => {
// Gives a distinct double-pulse "success" vibration
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
console.log("Task finished!");
};
const handleHeavyPress = () => {
// Simulates pressing a heavy, rigid physical button
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy);
console.log("Heavy action triggered!");
};
return (
<View style={styles.container}>
<View style={styles.buttonSpacing}>
<Button title="Complete Purchase" onPress={handleSuccess} color="green" />
</View>
<View style={styles.buttonSpacing}>
<Button title="Delete Item" onPress={handleHeavyPress} color="red" />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
buttonSpacing: { marginVertical: 10 }
});Industry Standards & Usability
- Use Haptics Like Seasoning: A pinch of salt makes food delicious; a cup of salt ruins the meal. If you add heavy haptic feedback to every single button, scroll, and keypress in your app, the user's hand will go numb, and they will uninstall your app. Reserve haptics for meaningful state changes: completing a form, pulling-to-refresh, toggling a switch, or triggering a destructive action like deleting a file.
Further Reading & References
If you want to dive deeper into configuration plugins, background tasks, or custom camera properties, the official Expo documentation is your best friend:
Challenge
Challenge: Build a Profile Image Updater Component
You are tasked with creating a React Native component, ProfileUpdater, that allows a user to update their profile picture by either taking a new photo with the device camera or selecting an existing one from the media library. This component must integrate functionality from expo-camera, expo-image-picker, and expo-haptics.
Requirements:
- State Management: The component must manage its state to conditionally render one of three views: the main profile view, the live camera feed, or the system image picker (which is launched externally).
- Take Photo Functionality:
- Create a button labeled "Take Photo".
- When pressed, the component must first verify camera permissions. If permissions are not granted, it must request them from the user.
- If permissions are granted, the component should render a full-screen
<CameraView>. - Inside the camera view, provide a button to capture an image. Upon capture, the component should update its state with the new image URI and return to the main profile view.
- Choose from Library Functionality:
- Create a button labeled "Choose from Library".
- When pressed, it must launch the device's native image library.
- Configure the image picker to only allow images (
MediaTypeOptions.Images), enable cropping with a square aspect ratio (aspect: [1, 1]), and most importantly, compress the selected image by setting thequalityto0.5. - Upon selection, the component should update its state with the selected image URI.
- Haptic Feedback:
- After a new image is successfully captured or selected, trigger a
Successnotification haptic feedback to confirm the action for the user.
- After a new image is successfully captured or selected, trigger a
- UI Display:
- The main view should display the current profile image (or a placeholder if none is set) and the two action buttons.
Expected result
The final code should be a complete and functional React Native component named ProfileUpdater.
Core Logic:
handleTakePhoto: Must correctly checkpermission.granted. If false, it should callrequestPermission(). If true, it should setshowCamera(true).pickImage: Must callImagePicker.launchImageLibraryAsyncwith an options object:{ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [1, 1], quality: 0.5 }. It must handle the result, checking thatresult.canceledis false before setting the image URI fromresult.assets[0].uri.capturePhoto: Must verify thatcameraRef.currentexists, then callawait cameraRef.current.takePictureAsync(). It must handle the returned photo object to set the image URI.- Haptics: Both
pickImageandcapturePhotofunctions must callHaptics.notificationAsync(Haptics.NotificationFeedbackType.Success)after successfully setting the new image URI.
Rendering Logic:
- The component must use conditional rendering. When
showCameraistrue, it must render the<CameraView>component. The<CameraView>must have itsrefprop set tocameraRef. ATouchableOpacityorButtonmust be rendered on top of the camera view to trigger thecapturePhotofunction. - When
showCameraisfalse, it must render an<Image>component whosesourceis set to{ uri: imageUri }ifimageUriis not null. It should also render two buttons that triggerhandleTakePhotoandpickImagerespectively.