React Native
Flash
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).
Exercise 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.
Show example solution
setFlash(prev => prev === FlashMode.off ? FlashMode.on : prev === FlashMode.on ? FlashMode.auto : FlashMode.off);
Test yourself
-
Write the flashMode prop
<Camera flashMode={____} style={{ flex: 1 }} />
Show answer
<Camera flashMode={flash} style={{ flex: 1 }} />
-
Which flash mode decides automatically?
flash === ? // flash fires in the dark
- FlashMode.on
- FlashMode.auto
- FlashMode.off
- FlashMode.always
Show answer
FlashMode.auto — FlashMode.auto decides based on the light meter.
-
Match each constant to its meaning
- FlashMode.on
- Always on
- FlashMode.off
- Off
- FlashMode.auto
- Automatic
- flashMode
- Camera prop
Next lesson: Summary - Camera