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