Flash
- React Native course
- Advanced
- Lesson 11/83
- 5 min
Learn flash and torch modes.
Flash mode
Flash gives light when taking a photo. expo-camera offers three modes: FlashMode.on (always on), FlashMode.off (off), FlashMode.auto (automatic). They are passed to the Camera component as the flashMode prop.
You keep the choice in state: const [flash, setFlash] = React.useState(FlashMode.off). When the user presses a button you change the flash mode. The FlashMode constants are imported from expo-camera: import { FlashMode } from 'expo-camera'. In dark settings the automatic mode is the most useful; the flash fires only when needed.
Flash constants
FlashMode carries three constants. FlashMode.on turns the flash on for every photo; it can be unnecessary in bright settings. FlashMode.off never turns the flash on; in dark settings the photo comes out dark. FlashMode.auto decides based on the camera's light meter.
State usually starts with FlashMode.off; the user turns it on if needed. When the button is pressed you can cycle the mode: off → on → auto → off. This pattern lets the user try the three modes in turn. You set up the cycle with setFlash(prev => prev === FlashMode.off ? FlashMode.on : prev === FlashMode.on ? FlashMode.auto : FlashMode.off).
Practice Write the flash cycle
Complete the empty cycleFlash function. Write setFlash(prev => prev === FlashMode.off ? FlashMode.on : prev === FlashMode.on ? FlashMode.auto : FlashMode.off). setFlash is passed as a parameter.
Starter code
import { FlashMode } from 'expo-camera';
export function cycleFlash(setFlash) {
// cycle the flash mode
}Sample solution
setFlash(prev => prev === FlashMode.off ? FlashMode.on : prev === FlashMode.on ? FlashMode.auto : FlashMode.off);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the flashMode prop
<Camera flashMode={____} style={{ flex: 1 }} />
<Camera flashMode={flash} style={{ flex: 1 }} />
Explanation: The flash state is given to the flashMode prop.
2 Which flash mode decides automatically?
flash === ? // flash fires in the dark- FlashMode.on
- FlashMode.auto Correct answer
- FlashMode.off
- FlashMode.always
Explanation: FlashMode.auto decides based on the light meter.
3 Match each constant to its meaning
| Term | Meaning |
|---|---|
FlashMode.on |
Always on |
FlashMode.off |
Off |
FlashMode.auto |
Automatic |
flashMode |
Camera prop |