Use an image picker (2024)

In this tutorial, learn how to use Expo Image Picker.

React Native provides built-in components that are standard building blocks used by every application, such as <View>, <Text>, and <Pressable>.We want to build a feature that isn't possible with these core components and API: selecting an image from the device's media library. For that, we will need a library.

To achieve this, we'll use an Expo SDK library called expo-image-picker.

expo-image-picker provides access to the system's UI to select images and videos from the phone's library or take a photo with the camera.

1

Install expo-image-picker

To install the library, run the following command:

Terminal

-

npx expo install expo-image-picker

Tip: Any time we install a new library in our project, we must stop the development server by pressing Ctrl + c in the terminal and then running the installation command.After the installation, we can start the development server again by running npx expo start from the same terminal window.

2

Pick an image from the device's media library

expo-image-picker provides the launchImageLibraryAsync() method that displays the system UI for choosing an image or a video from the device's media library.

We can use the button with the primary theme we created in the previous chapter to pick an image from the device's media library.We'll create a function to launch the device's image library to implement this functionality.

In App.js, import the expo-image-picker library and create a pickImageAsync() function inside the App component:

App.js

// ...rest of the import statements remain unchangedimport * as ImagePicker from 'expo-image-picker';export default function App() { const pickImageAsync = async () => { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, quality: 1, }); if (!result.canceled) { console.log(result); } else { alert('You did not select any image.'); } }; // ...rest of the code remains same}

Let's learn what the above code does.

  • The launchImageLibraryAsync() receives an object in which different options are specified.This object is an ImagePickerOptions object.We can pass the object to specify different options when invoking the method.
  • When allowsEditing is set to true, the user can crop the image during the selection process on Android and iOS but not on the web.

3

Update the button component

When the primary button gets pressed, we need to call the pickImageAsync() function.To call it, update the onPress property of the <Button> component in components/Button.js:

Button.js

export default function Button({ label, theme, onPress}) { // ...rest of the code remains same if (theme === "primary") { return ( <View> {/* ...rest of the code remains same */} <Pressable style={[styles.button, { backgroundColor: '#fff' }]} onPress={onPress} > </View> ); }}

In App.js, add the pickImageAsync() function to the onPress prop on the first <Button>.

App.js

export default function App() { // ...rest of the code remains same return ( <View style={styles.container}> {/* ...rest of the code remains same */} <Button theme="primary" label="Choose a photo" onPress={pickImageAsync} /> </View> );}

The pickImageAsync() function is responsible for invoking ImagePicker.launchImageLibraryAsync() and then handling the result.The launchImageLibraryAsync() method returns an object containing information about the selected image.

To demonstrate what properties the result object contains, here is an example result object:

{ "assets": [ { "assetId": null, "base64": null, "duration": null, "exif": null, "height": 4800, "rotation": null, "type": "image", "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%username%252Fsticker-smash-47-beta/ImagePicker/77c4e56f-4ccc-4c83-8634-fc376597b6fb.jpeg", "width": 3200 } ], "canceled": false}

4

Use the selected image

The result object provides the assets array, which contains the uri of the selected image.Let's take this value from the image picker and use it to show the selected image in the app.

Modify the App.js file in the following steps:

  • Declare a state variable called selectedImage using the useState hook from React.We'll use this state variable to hold the URI of the selected image.
  • Update the pickImageAsync() function to save the image URI in the selectedImage state variable.
  • Then, pass the selectedImage as a prop to the ImageViewer component.

App.js

import { useState } from 'react';// ...rest of the import statements remain unchangedexport default function App() { const [selectedImage, setSelectedImage] = useState(null); const pickImageAsync = async () => { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, quality: 1, }); if (!result.canceled) { setSelectedImage(result.assets[0].uri); } else { alert('You did not select any image.'); } }; return ( <View style={styles.container}> <View style={styles.imageContainer}> <ImageViewer placeholderImageSource={PlaceholderImage} selectedImage={selectedImage} /> </View> {/* ...rest of the code remains same */} </View> );}

Now, modify the components/ImageViewer.js file to conditionally display the selected image in place of the placeholder image.We'll need to pass the selectedImage prop to the component.

The source of the image is getting long, so let's also move it to a separate variable called imageSource.Then, pass it as the value of the source prop on the <Image> component.

Image picker

export default function ImageViewer({ placeholderImageSource, selectedImage }) { const imageSource = selectedImage ? { uri: selectedImage } : placeholderImageSource; return <Image source={imageSource} style={styles.image} />;}

In the above snippet, the <Image> component uses a conditional operator to load the source of the image.This is because the image picked from the image picker is a uri string,not a local asset like the placeholder image.

Let's take a look at our app now:

The images used for the demo in this tutorial were picked from Unsplash.

Next step

We added the functionality to pick an image from the device's media library.

Create an emoji picker modal

In the next chapter, we'll learn how to create an emoji picker modal component.

Use an image picker (2024)
Top Articles
Shortages 2024: What supplies are still at risk after years of disruption?
Why alternative financial services are growing in popularity
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 5760

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.