1--- 2title: Use an image picker 3--- 4 5import { SnackInline, Terminal } from '~/ui/components/Snippet'; 6import Video from '~/components/plugins/Video'; 7import { LinkBase } from '~/ui/components/Text'; 8 9React 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. 10 11To achieve this, we'll use an Expo SDK library called <LinkBase href="/versions/latest/sdk/imagepicker" openInNewTab>`expo-image-picker`</LinkBase>. 12 13> `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. 14 15## Step 1: Install expo-image-picker 16 17To install the library, run the following command: 18 19<Terminal cmd={['$ npx expo install expo-image-picker']} /> 20 21> **Tip:** Any time we install a new library in our project, we must stop the development server by pressing <kbd>Ctrl</kbd> + <kbd>c</kbd> 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. 22 23## Step 2: Pick an image from the device's media library 24 25`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. 26 27We 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. 28 29In **App.js**, import the `expo-image-picker` library and create a `pickImageAsync()` function inside the `App` component: 30 31{/* prettier-ignore */} 32```jsx App.js 33// ...rest of the import statements remain unchanged 34/* @info Import the ImagePicker. */ import * as ImagePicker from 'expo-image-picker'; /* @end */ 35 36export default function App() { 37 const pickImageAsync = async () => { 38 /* @info Pass image picker options to launchImageLibraryAsync() */ 39 let result = await ImagePicker.launchImageLibraryAsync({ 40 allowsEditing: true, 41 quality: 1, 42 }); 43 /* @end */ 44 45 if (!result.canceled) { 46 /* @info If the image is picked, print its information in terminal window. */ 47 console.log(result); 48 /* @end */ 49 } else { 50 /* @info If the user does not picks an image, show an alert. */ 51 alert('You did not select any image.'); 52 /* @end */ 53 } 54 }; 55 56 // ...rest of the code remains same 57} 58``` 59 60Let's learn what the above code does. 61 62- The `launchImageLibraryAsync()` receives an object in which different options are specified. This object is an <LinkBase href="/versions/latest/sdk/imagepicker/#imagepickeroptions" openInNewTab>`ImagePickerOptions` object</LinkBase>. We can pass the object to specify different options when invoking the method. 63- 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. 64 65## Step 3: Update the button component 66 67When 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**: 68 69{/* prettier-ignore */} 70```jsx Button.js 71export default function Button({ label, theme, /* @info Pass this prop to trigger the handler method from the parent component. */ onPress/* @end */}) { 72 // ...rest of the code remains same 73 if (theme === "primary") { 74 return ( 75 <View> 76 /* ...rest of the code remains same */ 77 <Pressable 78 style={[styles.button, { backgroundColor: '#fff' }]} 79 /* @info */ onPress={onPress} /* @end */ 80 > 81 </View> 82 ); 83 } 84} 85``` 86 87In **App.js**, add the `pickImageAsync()` function to the `onPress` prop on the first `<Button>`. 88 89{/* prettier-ignore */} 90```jsx App.js 91export default function App() { 92 // ...rest of the code remains same 93 94 return ( 95 <View style={styles.container}> 96 /* ...rest of the code remains same */ 97 <Button theme="primary" label="Choose a photo" /* @info */ onPress={pickImageAsync} /* @end */ /> 98 </View> 99 ); 100} 101``` 102 103The `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. 104 105To demonstrate what properties the `result` object contains, here is an example result object: 106 107```json 108{ 109 "assets": [ 110 { 111 "assetId": null, 112 "base64": null, 113 "duration": null, 114 "exif": null, 115 "height": 4800, 116 "rotation": null, 117 "type": "image", 118 "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%username%252Fsticker-smash-47-beta/ImagePicker/77c4e56f-4ccc-4c83-8634-fc376597b6fb.jpeg", 119 "width": 3200 120 } 121 ], 122 "canceled": false, 123 "cancelled": false 124} 125``` 126 127## Step 4: Use the selected image 128 129The `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. 130 131Modify the **App.js** file in the following steps: 132 133- Declare a state variable called `selectedImage` using the <LinkBase href="https://reactjs.org/docs/hooks-state.html" openInNewTab>`useState`</LinkBase> hook from React. We'll use this state variable to hold the URI of the selected image. 134- Update the `pickImageAsync()` function to save the image URI in the `selectedImage` state variable. 135- Then, pass the `selectedImage` as a prop to the `ImageViewer` component. 136 137{/* prettier-ignore */} 138```jsx App.js 139/* @info Import useState hook from React. */ import { useState } from 'react'; /* @end */ 140// ...rest of the import statements remain unchanged 141 142export default function App() { 143 /* @info Create a state variable that will hold the value of selected image. */ 144 const [selectedImage, setSelectedImage] = useState(null); 145 /* @end */ 146 147 const pickImageAsync = async () => { 148 let result = await ImagePicker.launchImageLibraryAsync({ 149 allowsEditing: true, 150 quality: 1, 151 }); 152 153 if (!result.canceled) { 154 /* @info Pick the first uri from the assets array. Also, there is only one image selected at a time so you don't have to change this. */ 155 setSelectedImage(result.assets[0].uri); 156 /* @end */ 157 } else { 158 alert('You did not select any image.'); 159 } 160 }; 161 162 return ( 163 <View style={styles.container}> 164 <View style={styles.imageContainer}> 165 /* @info Pass the selected image URI to the ImageViewer component. */<ImageViewer 166 placeholderImageSource={PlaceholderImage} 167 selectedImage={selectedImage} 168 /> 169 /* @end */ 170 </View> 171 /* ...rest of the code remains same */ 172 </View> 173 ); 174} 175``` 176 177Now, 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. 178 179The 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. 180 181<SnackInline 182label="Image picker" 183templateId="tutorial/02-image-picker/App" 184dependencies={['expo-image-picker', 'expo-status-bar', '@expo/vector-icons', '@expo/vector-icons/FontAwesome']} 185files={{ 186'assets/images/background-image.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/503001f14bb7b8fe48a4e318ad07e910', 187'components/ImageViewer.js': 'tutorial/02-image-picker/ImageViewer.js', 188'components/Button.js': 'tutorial/02-image-picker/Button.js' 189}}> 190 191{/* prettier-ignore */} 192```jsx 193export default function ImageViewer({ placeholderImageSource, /* @info Pass the selectedImage prop.*/selectedImage/* @end */ }) { 194 /* @info If the selected image is not null, show the image from the device, otherwise, show the placeholder image. */ 195 const imageSource = selectedImage !== null 196 ? { uri: selectedImage } 197 : placeholderImageSource; 198 /* @end */ 199 200 return <Image /* @info */source={imageSource}/* @end */ style={styles.image} />; 201} 202``` 203 204</SnackInline> 205 206In 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 <LinkBase href="https://reactnative.dev/docs/images#network-images" openInNewTab>`uri` string</LinkBase>, not a local asset like the placeholder image. 207 208Let's take a look at our app now: 209 210<Video file="tutorial/03-image-picker-demo.mp4" /> 211 212> The images used for the demo in this tutorial were picked from [Unsplash](https://unsplash.com). 213 214## Up next 215 216We added the functionality to pick an image from the device's media library. 217 218In the next chapter, we'll learn how to [create an emoji picker modal component](/tutorial/create-a-modal). 219