Taking pictures
- React Native course
- Advanced
- Lesson 9/83
- 5 min
Learn to take pictures with takePictureAsync.
takePictureAsync
The Camera component has a ref. You call the photo capture function through this ref: cameraRef.current.takePictureAsync(). The function returns an asynchronous object; the uri field carries the file path of the captured photo.
To create a ref you use React.useRef(null); you attach it as a <Camera ref={cameraRef} /> prop. You bind the capture function to a button's onPress. Example: const photo = await cameraRef.current.takePictureAsync(). You can then save the returned object's uri property to the gallery or show it on the screen.
Attaching a ref
To attach the ref to the camera you use the ref prop. Example: const cameraRef = React.useRef(null) and <Camera ref={cameraRef} style={{{ flex: 1 }}} />. After attaching, cameraRef.current points to the camera component; you can call functions like takePictureAsync on it.
If the ref is not attached, cameraRef.current stays null; the function call errors. So always attach the ref to the camera. When binding the capture function to a button you write onPress={takePhoto}; the takePhoto function uses the ref.
Practice Take a photo and log the uri
Complete the takePhoto function. Call const photo = await cameraRef.current.takePictureAsync(); log the file path with console.log(photo.uri). cameraRef is already defined.
Starter code
export async function takePhoto(cameraRef) {
// take a photo and log the uri
}Sample solution
const photo = await cameraRef.current.takePictureAsync();
console.log(photo.uri);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each part to its role
| Term | Meaning |
|---|---|
useRef |
Creates a ref |
cameraRef.current |
Access through ref |
takePictureAsync |
Takes a photo |
uri |
File path |
2 How is takePictureAsync called?
const photo = await cameraRef.current.??()- cameraRef.takePictureAsync()
- Camera.takePictureAsync()
- takePicture(cameraRef)
- cameraRef.current.takePictureAsync() Correct answer
Explanation: It is called through the ref's current property.
3 Ref creation
const cameraRef = React.____(null);
const cameraRef = React.useRef(null);
Explanation: Write useRef; refs are created with useRef.