React Native
launchImageLibraryAsync
Learn to pick images with launchImageLibraryAsync.
launchImageLibraryAsync
To pick an image from the gallery you call ImagePicker.launchImageLibraryAsync. The function returns an object; the canceled field is true if the user canceled the selection, the assets field carries the picked images. Since assets is an array you get the first image with assets[0].
The function takes an options object; for example { mediaTypes: ImagePicker.MediaTypeOptions.Images } shows only images. You await the result object. Example: const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images }). The code waits until the user makes a selection.
The result object
The returned object has two important fields. The canceled field becomes true if the user canceled the selection; in this case assets stays empty. The assets field is an array; each element is an image object carrying fields like uri, width, height.
To get the first image you write result.assets[0]. For the cancel check you use the if (result.canceled) return; pattern. These two checks together form a safe selection flow. Trying to process the image before a selection is made raises an error; so the cancel check is mandatory.
Exercise Pick an image from the gallery
Complete the pickImage function. Call const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images }). If result.canceled, return null. Otherwise return result.assets[0].uri.
Show example solution
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
if (result.canceled) return null;
return result.assets[0].uri;
Test yourself
-
Write the result variable
const ____ = await ImagePicker.launchImageLibraryAsync(options);
Show answer
const result = await ImagePicker.launchImageLibraryAsync(options);
-
Match each field to its meaning
- canceled
- Cancel state
- assets
- Picked image array
- uri
- Image path
- assets[0]
- First image
-
What is done when canceled?
if (result.canceled) { ... }
- Return early; no image
- Process the image
- Close the app
- Throw an error
Show answer
Return early; no image — When canceled, return early; the image is not processed.
Next lesson: launchCameraAsync