1--- 2title: Take screenshot 3--- 4 5import { SnackInline, Terminal } from '~/ui/components/Snippet'; 6import Video from '~/components/plugins/Video'; 7import { LinkBase } from '~/ui/components/Text'; 8 9In this chapter, we will learn how to take a screenshot using a third-party library and save it on the device's media library. We'll use the following libraries <LinkBase href="https://github.com/gre/react-native-view-shot" openInNewTab> `react-native-view-shot`</LinkBase> that allows taking a screenshot, and <LinkBase href="/versions/latest/sdk/media-library/" openInNewTab>`expo-media-library`</LinkBase> that allows accessing a device's media library to save an image. 10 11> So far, we have been using some third-party libraries such as `react-native-gesture-handler`, `react-native-reanimated`, and now `react-native-view-shot`. We can find hundreds of other third-party libraries on [React Native Directory](https://reactnative.directory/). 12 13## Step 1: Install libraries 14 15To install both libraries, run the following commands: 16 17<Terminal cmd={['$ npx expo install react-native-view-shot expo-media-library']} /> 18 19## Step 2: Prompt for permissions 20 21When creating an app that requires access to potentially sensitive information, such as access to the media library, we must first request the user's permission. 22 23`expo-media-library` provides a `usePermissions()` hook that gives the permission `status`, and a `requestPermission()` method to ask for access to the media library when permission is not granted. 24 25Initially, when the app loads for the first time and the permission status is neither granted nor denied, the value of the `status` is `null`. When asked for permission, a user can either grant the permission or deny it. We can add a condition to check if it is `null`, and if it is, trigger the `requestPermission()` method. 26 27Add the following code snippet inside the `<App>` component: 28 29{/* prettier-ignore */} 30```jsx App.js 31/* @info Import expo-media-library. */import * as MediaLibrary from 'expo-media-library';/* @end */ 32 33// ...rest of the code remains same 34 35export default function App() { 36 /* @info Add this statement to import the permissions status and requestPermission() method from the hook. */const [status, requestPermission] = MediaLibrary.usePermissions();/* @end */ 37 // ...rest of the code remains same 38 39 /* @info Add an if statement to check the status of permission. The requestPermission() method will trigger a dialog box for the user to grant or deny the permission. */ 40 if (status === null) { 41 requestPermission();/* @end */ 42 } 43 44 // ...rest of the code remains same 45} 46``` 47 48Once the permission is given, the value of the `status` changes to `granted`. 49 50## Step 3: Picking a library to take screenshots 51 52To allow the user to take a screenshot within the app, we'll use [`react-native-view-shot`](https://github.com/gre/react-native-view-shot). It allows capturing a `<View>` as an image. 53 54Let's import it into **App.js** file: 55 56```jsx App.js 57import { captureRef } from 'react-native-view-shot'; 58``` 59 60## Step 4: Create a ref to save the current view 61 62The `react-native-view-shot` library provides a method called `captureRef()` that captures a screenshot of a `<View>` in the app and returns the URI of the screenshot image file. 63 64To capture a `<View>`, wrap the `<ImageViewer>` and `<EmojiSticker>` components inside a `<View>` and then pass a reference to it. Using the `useRef()` hook from React, let's create an `imageRef` variable inside `<App>`. 65 66{/* prettier-ignore */} 67```jsx App.js 68import { useState, /* @info Import the useRef hook from React. */useRef/* @end */ } from 'react'; 69 70export default function App() { 71 /* @info Create an imageRef variable. */ const imageRef = useRef();/* @end */ 72 73 // ...rest of the code remains same 74 75 return ( 76 <GestureHandlerRootView style={styles.container}> 77 <View style={styles.imageContainer}> 78 /* @info Add a View component to wrap the ImageViewer and EmojiSticker inside it. */<View ref={imageRef} collapsable={false}>/* @end */ 79 <ImageViewer placeholderImageSource={PlaceholderImage} selectedImage={selectedImage} /> 80 {pickedEmoji !== null ? ( 81 <EmojiSticker imageSize={40} stickerSource={pickedEmoji} /> 82 ) : null} 83 /* @info */</View>/* @end */ 84 </View> 85 /* ...rest of the code remains same */ 86 </GestureHandlerRootView> 87 ); 88} 89``` 90 91The `collapsible` prop is set to `false` in the above snippet because this `<View>` component is used to take a screenshot of the background image and the emoji sticker. The rest of the contents of the app screen (such as buttons) are not part of the screenshot. 92 93## Step 5: Capture a screenshot and save it 94 95Now we can capture a screenshot of the view by calling the `captureRef()` method from `react-native-view-shot` inside the `onSaveImageAsync()` function. `captureRef()` accepts an optional argument where we can pass the `width` and `height` of the area we'd like to capture a screenshot for. We can read more about available options in <LinkBase href="https://github.com/gre/react-native-view-shot#capturerefview-options-lower-level-imperative-api" openInNewTab>the library's documentation</LinkBase>. 96 97The `captureRef()` method returns a promise that fulfills with the URI of the captured screenshot. We will pass this URI as a parameter to <LinkBase href="/versions/latest/sdk/media-library/#medialibrarysavetolibraryasynclocaluri" openInNewTab>`MediaLibrary.saveToLibraryAsync()`</LinkBase>, which will save the screenshot to the device's media library. 98 99Update the `onSaveImageAsync()` function with the following code: 100 101<SnackInline 102label="Take a screenshot" 103templateId="tutorial/07-screenshot/App" 104dependencies={['expo-image-picker', '@expo/vector-icons/FontAwesome', '@expo/vector-icons', 'expo-status-bar', '@expo/vector-icons/MaterialIcons', 'react-native-gesture-handler', 'react-native-reanimated', 'react-native-view-shot', 'expo-media-library']} 105files={{ 106 'assets/images/background-image.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/503001f14bb7b8fe48a4e318ad07e910', 107 'assets/images/emoji1.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/be9751678c0b3f9c6bf55f60de815d30', 108 'assets/images/emoji2.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/7c0d14b79e134d528c5e0801699d6ccf', 109 'assets/images/emoji3.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/d713e2de164764c2ab3db0ab4e40c577', 110 'assets/images/emoji4.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/ac2163b98a973cb50bfb716cc4438f9a', 111 'assets/images/emoji5.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/9cc0e2ff664bae3af766b9750331c3ad', 112 'assets/images/emoji6.png': 'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/ce614cf0928157b3f7daa3cb8e7bd486', 113 'components/ImageViewer.js': 'tutorial/02-image-picker/ImageViewer.js', 114 'components/Button.js': 'tutorial/03-button-options/Button.js', 115 'components/CircleButton.js': 'tutorial/03-button-options/CircleButton.js', 116 'components/IconButton.js': 'tutorial/03-button-options/IconButton.js', 117 'components/EmojiPicker.js': 'tutorial/04-modal/EmojiPicker.js', 118 'components/EmojiList.js': 'tutorial/05-emoji-list/EmojiList.js', 119 'components/EmojiSticker.js': 'tutorial/06-gestures/CompleteEmojiSticker.js', 120}}> 121 122{/* prettier-ignore */} 123```jsx 124export default function App() { 125 /* @info Replace the comment with the code to capture the screenshot and save the image. */ 126 const onSaveImageAsync = async () => { 127 try { 128 const localUri = await captureRef(imageRef, { 129 height: 440, 130 quality: 1, 131 }); 132 133 await MediaLibrary.saveToLibraryAsync(localUri); 134 if (localUri) { 135 alert("Saved!"); 136 } 137 } catch (e) { 138 console.log(e); 139 } 140 }; 141 /* @end */ 142 // ...rest of the code remains same 143} 144``` 145 146</SnackInline> 147 148Now, choose a photo and add a sticker. Then tap the “Save” button. We should see the following result: 149 150<Video file="tutorial/saving-screenshot.mp4" /> 151 152## Up next 153 154The `react-native-view-shot` and `expo-media-library` work only on Android and iOS, but we'd like our app to work on web as well. 155 156In the next chapter, let's learn how to [handle the differences between mobile and web platforms](/tutorial/platform-differences). 157