# react-native-view-shot ![](https://img.shields.io/npm/v/react-native-view-shot.svg) ![](https://img.shields.io/badge/react--native-0.80%2B-05F561.svg) Capture a React Native view to an image. ## New Architecture Support This library fully supports React Native's **new architecture** (Fabric + TurboModules) from version 4.0+. **Requirements:** - React Native >= 0.80.0 - Node.js >= 20.19.4 Both old and new architectures are supported for seamless migration. ## Install ```bash npm install react-native-view-shot # or with Yarn yarn add react-native-view-shot # In Expo npx expo install react-native-view-shot ``` **Since React Native 0.60+, [autolink](https://github.com/react-native-community/cli/blob/main/docs/autolinking.md) handles the linking automatically.** On iOS, install the CocoaPods dependencies: ```bash npx pod-install ``` ### Web On web (`react-native-web`, Expo web), captures are rendered with [html2canvas-pro](https://github.com/yorickshan/html2canvas-pro). It is an optional peer dependency, so it is not installed on native-only projects — add it yourself when targeting the web: ```bash npm install html2canvas-pro ``` It is loaded lazily on the first capture. If it is missing, your bundler (webpack, Metro) fails at build time with `Can't resolve 'html2canvas-pro'`; in environments that resolve modules at runtime, `captureRef` rejects with an explicit install hint instead. `react-native` is also an optional peer dependency, so a web-only project can install `react-native-web` without pulling `react-native` (alias `react-native` to `react-native-web` in your bundler as usual). The library reads the `__DEV__` global, as React Native code does. Metro and Expo define it for you; with a custom webpack/esbuild setup you must define it yourself, otherwise the page throws `ReferenceError: __DEV__ is not defined`: ```js // webpack.config.js new webpack.DefinePlugin({ __DEV__: JSON.stringify(process.env.NODE_ENV !== "production") }) // esbuild --define:__DEV__=false ``` ## High Level API ```js import React, {useCallback, useEffect, useRef} from "react"; import {Image, ScrollView, Text} from "react-native"; import ViewShot from "react-native-view-shot"; function ExampleCaptureOnMountManually() { const ref = useRef(); useEffect(() => { // on mount ref.current .capture() .then(uri => { console.log("do something with ", uri); }) .catch(console.error); }, []); return ( ...Something to rasterize... ); } // alternative function ExampleCaptureOnMountSimpler() { const onCapture = useCallback(uri => { console.log("do something with ", uri); }, []); return ( ...Something to rasterize... ); } // waiting an image function ExampleWaitingCapture({imageSource}) { const ref = useRef(); const onImageLoad = useCallback(() => { ref.current .capture() .then(uri => { console.log("do something with ", uri); }) .catch(console.error); }, []); return ( ...Something to rasterize... ); } // capture ScrollView content // NB: you may need to go the "imperative way" to use snapshotContentContainer with the scrollview ref instead function ExampleCaptureScrollContent() { const onCapture = useCallback(uri => { console.log("do something with ", uri); }, []); return ( ...The Scroll View Content Goes Here... ); } ``` **Props:** - **`children`**: the actual content to rasterize. - **`options`**: the same options as in `captureRef` method. - **`captureMode`** (string): - if not defined (default). the capture is not automatic and you need to use the ref and call `capture()` yourself. - `"mount"`. Capture the view once at mount. Image loading is not awaited; omit `captureMode` and call `viewShotRef.current.capture()` after `Image#onLoad` when needed. - `"continuous"` EXPERIMENTAL, this will capture A LOT of images continuously. For very specific use-cases. - `"update"` EXPERIMENTAL, this will capture images each time React redraw (on did update). For very specific use-cases. - **`onCapture`**: when a `captureMode` is defined, this callback will be called with the capture result. - **`onCaptureFailure`**: when a `captureMode` is defined, this callback will be called when a capture fails. - **`onLayout`**: forwarded to the inner `View`. - **`style`**: style of the inner `View`. ## `captureRef(view, options)` lower level imperative API ```js import {captureRef} from "react-native-view-shot"; captureRef(viewRef, { format: "jpg", quality: 0.8, }).then( uri => console.log("Image saved to", uri), error => console.error("Oops, snapshot failed", error), ); ``` Returns a Promise of the image URI. - **`view`** is a reference to a React Native component. - **`options`** may include: - [Android, iOS] **`fileName`** _(string)_: the prefix of the file name when `result` is `"tmpfile"`. A unique suffix and the format extension are appended, so captures never overwrite each other. Must be at least 3 characters long. Characters other than letters, digits, `.`, `_` and `-` are replaced with `_` (with a warning), so the returned path is safe to use in a `file://` URL. - [Windows] **`path`** _(string)_: a plain file name (no directories) to write when `result` is `"tmpfile"`, created in the app's `LocalFolder` (persistent storage: call `releaseCapture` when done). Used as-is (include the extension); an existing file with that name is overwritten. Defaults to a random GUID name. - **`width`** / **`height`** _(number)_: the width and height of the final image (resized from the View bound. don't provide it if you want the original pixel size). Default unit: points/dp on iOS and Windows, pixels on Android and web. Use `sizeUnit` in cross-platform code. - **`sizeUnit`** _(`"dp"` | `"px"`)_: unit of `width` / `height`, the same on every platform: `"dp"` gives an image of `round(value × PixelRatio.get())` pixels, `"px"` `round(value)` pixels. When omitted, each platform keeps its default unit. - **`format`** _(string)_: `png` or `jpg`, plus `webp` and `raw` on Android. Defaults to `png`. `webm` is a deprecated alias for `webp`; it produces WebP image data, not a video. - **`quality`** _(number)_: the quality. 0.0 - 1.0 (default). (only available on lossy formats like jpg) - **`result`** _(string)_, the method you want to use to save the snapshot, one of: - `"tmpfile"` (default): save to a temporary file _(that will only exist for as long as the app is running)_. - `"base64"`: encode as base64 and returns the raw string. Use only with small images as this may result of lags (the string is sent over the bridge). _N.B. This is not a data uri, use `data-uri` instead_. - `"data-uri"`: same as `base64` but also includes the [Data URI scheme](https://en.wikipedia.org/wiki/Data_URI_scheme) header. - `"zip-base64"` (Android only): zlib-compressed, then base64-encoded. On other platforms it falls back to the default `"tmpfile"` result with a `console.warn`. See [zip-base64](#zip-base64). - **`snapshotContentContainer`** _(bool)_: if true and when the captured ref is a `ScrollView`, the entire scrollable content is captured rather than just the visible viewport. Works on both iOS and Android (the lib temporarily expands the ScrollView to its full content size during the draw, then restores). **Android caveat**: only vertical `` is supported — horizontal scroll views (``, backed by `HorizontalScrollView`) are not expanded and will fall back to capturing the visible bounds. iOS handles both axes via `UIScrollView`. **Windows: not supported** — UWP's `RenderTargetBitmap` respects the live `ScrollViewer` clip and we have no reliable way to capture the full scrollable area; the option is ignored and only the visible viewport is captured (a `console.warn` fires). **FlatList note**: virtualization (`removeClippedSubviews`, `windowSize`) means off-screen items aren't mounted at the React layer and will be missing from the capture. Set `removeClippedSubviews={false}` and a large `windowSize`, or use a plain `` for content up to a few hundred items. See `example/src/screens/ScrollViewTestScreen.tsx` for a working demo. - [Android] **`handleGLSurfaceViewOnAndroid`** _(bool)_: also capture `SurfaceView`s (e.g. GL views) in the view tree. Defaults to `false` (it can have a significant performance cost). - [iOS] **`useRenderInContext`** _(bool)_: change the iOS snapshot strategy to use method `renderInContext` instead of `drawViewHierarchyInRect` which may help for some use cases. ## `releaseCapture(uri)` This method release a previously captured `uri`. For tmpfile it will clean them out, for other result types it just won't do anything. NB: the tmpfile captures are automatically cleaned out after the app closes, so you might not have to worry about this unless advanced usecases. The `ViewShot` component will use it each time you capture more than once (useful for continuous capture to not leak files). ## `captureScreen()` Android, iOS, Windows, and Web ```js import {captureScreen} from "react-native-view-shot"; captureScreen({ format: "jpg", quality: 0.8, }).then( uri => console.log("Image saved to", uri), error => console.error("Oops, snapshot failed", error), ); ``` This method will capture the contents of the currently displayed screen as a native hardware screenshot (on web, it captures `document.body`). It does not require a ref input, as it does not work at the view level. This means that ScrollViews will not be captured in their entirety - only the portions currently visible to the user. Returns a Promise of the image URI. - **`options`**: the same options as in `captureRef` method. - [Android] On API 26+, `captureScreen` snapshots the window via `PixelCopy`, so `TextureView` content (maps, video, camera previews that use one) keeps its on-screen z-order under the views above it. A `SurfaceView` is a separate surface and is not in a window snapshot, so with `handleGLSurfaceViewOnAndroid` `captureScreen` keeps the view-draw path that captures each `SurfaceView`. Any failure silently falls back to the view-draw path used by `captureRef`. `captureRef` itself always uses the view-draw path: a window crop of a partially obscured view would capture the occluding content, so `TextureView`s there are still repainted on top (see [#492](https://github.com/gre/react-native-view-shot/issues/492) and [#150](https://github.com/gre/react-native-view-shot/issues/150)). ## Masking Sensitive Content (``) `` allows you to redact or hide sensitive on-screen content (e.g. credit card details, personal data, or passwords) from captured screenshots. Children of `` render normally on-screen for the user, but in snapshots produced by `captureRef` or `captureScreen`, the masked view is replaced with a solid colored rectangle. ```tsx import React, {useRef} from "react"; import {View, Text, Button} from "react-native"; import ViewShot, {MaskView, captureRef} from "react-native-view-shot"; export function SensitiveScreen() { const containerRef = useRef(null); const takeSnapshot = async () => { const uri = await captureRef(containerRef, {format: "png"}); console.log("Captured image with masked credit card:", uri); }; return ( Order Confirmation {/* Renders normally on-screen, but replaced by a solid black box in screenshots */} Card Number: 4111 •••• •••• 1234