CodeBlanks Logo Icon CodeBlanks

Front/back camera

Learn to switch between front and back cameras.

Front and back camera

The phone has two cameras: front (selfie) and back. expo-camera makes this choice with the CameraType constant. CameraType.back is the back camera and CameraType.front is the front camera. They are passed to the Camera component as the type prop.

You keep the choice in state: const [type, setType] = React.useState(CameraType.back). When the button is pressed you switch with setType(type === CameraType.back ? CameraType.front : CameraType.back). This simple toggle pattern lets the user switch the camera with a single tap.

The toggle pattern

The camera switch button is bound to a toggle function. The function looks at the current type value and flips it. The syntax: setType(prev => prev === CameraType.back ? CameraType.front : CameraType.back). Here prev represents the previous value.

Using prev in state updates is the most robust method; because it always takes the current value on consecutive calls. You bind this function to the button's onPress. Each time the user taps the button, the camera switches between front and back; this is a standard feature of modern camera apps.

Practice Add a camera switch button

Complete the empty toggleCamera function. Write setType(prev => prev === CameraType.back ? CameraType.front : CameraType.back). type and setType are passed as parameters.

Starter code

App.js
import { CameraType } from 'expo-camera';

export function toggleCamera(type, setType) {
  // switch the camera type
}

Sample solution

App.js
setType(prev => prev === CameraType.back ? CameraType.front : CameraType.back);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the type prop

Question
<Camera ____={type} style={{ flex: 1 }} />
Answer
<Camera type={type} style={{ flex: 1 }} />

Explanation: The type prop takes the camera choice.

2 Match each constant to its meaning

Term Meaning
CameraType.back Back camera
CameraType.front Front camera
type Choice prop
setType Updates the choice

3 What is used when writing a toggle with setType?

App.js
setType(?? => ?? === CameraType.back ? CameraType.front : CameraType.back)
  • prev Correct answer
  • current
  • next
  • type

Explanation: prev represents the current value.

All lessons in Advanced