# react-native-view-shot  
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
);
}
```
### Props
- **`maskColor`** _(ColorValue | string)_: The color of the solid rectangle drawn over the view in snapshots. Defaults to `"#000000"` (opaque black). Normalized in JS via React Native's `processColor()`, supporting:
- 6-digit hex: `"#FF5500"`
- 3-digit hex: `"#F50"`
- 8-digit hex (with alpha): `"#FF550080"`
- `rgb()` and `rgba()`: e.g. `"rgba(0, 0, 0, 0.5)"`
- Named CSS colors: e.g. `"red"`, `"blue"`, `"black"`, `"white"`, etc.
- Transparent colors: e.g. `"transparent"` or `"rgba(0,0,0,0)"`
> [!WARNING]
> **Alpha & Redaction Security**: If a `maskColor` with an alpha channel below 255 is provided (e.g. `"transparent"`, `"rgba(..., alpha < 1)"`, or 8-digit hex with alpha < 255), underlying sensitive content will remain partially or completely visible in screenshots. For guaranteed redaction, always use an opaque color.
- **`style`**: Style forwarded to the container `View`. Enforces `overflow: "hidden"` to prevent overflowing child content from leaking into captures.
- **`children`**: Content that will be rendered on-screen, but occluded in captures.
- All other standard `ViewProps` (except `nativeID`, which is managed internally) are supported.
### Behavior & Limitations
- **Zero UI Flicker**: Masking is executed post-rasterization directly on the offscreen canvas/graphics context before encoding. Live native views are never mutated or hidden.
- **Hardware Overlay Protection**: Hardware overlays (`TextureView` / `SurfaceView` on Android, video and GPU layers on iOS) descending from a `` are suppressed and covered by the mask.
- **Overflow & Ancestor Clipping**: `` enforces `overflow: "hidden"` on its container so children extending outside its bounds cannot leak into captures. Masks also strictly respect ancestor clipping bounds (e.g. `overflow: "hidden"` containers or `ScrollView` viewports) and will never paint over content outside clipped parent boundaries.
- **Transforms & Nested Scroll**: Nested views, rotation/scaling transforms, and scroll containers (`snapshotContentContainer` both `true` and `false`) are automatically tracked and masked at their exact relative positions.
- **Platform Limitations**:
- **Android ``**: On Android, React Native's `` renders into an independent native `Dialog` window rather than the activity decor view. Full-window captures using `captureScreen` target the activity window and do not capture views in separate dialog windows. To capture and mask content inside an Android modal, call `captureRef` on a view within that modal.
- **Active Animations & PixelCopy (`captureScreen`)**: On Android API 26+, `captureScreen` snapshots the hardware window via `PixelCopy`. Because `PixelCopy` reads the hardware surface asynchronously, during rapid continuous animation or fling scrolling the compositor buffer and View hierarchy coordinates may differ by one frame. For guaranteed frame-synchronous masking during active scrolling or animations, use `captureRef` (which renders views and masks in the exact same synchronous UI-thread pass).
- **Web and Windows**: MaskView native masking is currently supported on Android and iOS. On Web and Windows, native masking is not supported; in development builds (`__DEV__`), a warning is logged so developers never inadvertently assume content is masked on these platforms. Always protect sensitive data appropriately when capturing on Web/Windows.
## Examples
### Native Example (iOS & Android)
[Checkout react-native-view-shot-example](example) - Comprehensive example app demonstrating all features on iOS and Android.
### Web Example
[Checkout react-native-view-shot-web-example](example-web) - Web example demonstrating how the library works in browsers using html2canvas-pro.
### Expo and Windows Examples
[example-expo](example-expo) (Expo dev client) and [example-windows](example-windows) (React Native Windows).
## Interoperability Table
> Snapshots are not guaranteed to be pixel perfect. It also depends on the platform. Here is some difference we have noticed and how to workaround.
Model tested: iPhone 6 (iOS), Nexus 5 (Android).
| System | iOS | Android | Windows | Web |
| ------------------- | --- | --------------- | --------------- | ------------------- |
| View,Text,Image,.. | YES | YES | YES | YES |
| WebView | YES | YES1 | YES | N/A |
| gl-react v2 | YES | NO2 | NO3 | NO3 |
| react-native-video | NO | NO | NO | NO |
| react-native-maps | YES | NO4 | NO3 | NO3 |
| react-native-svg | YES | YES | maybe? | LIMITED5 |
| react-native-camera | NO | YES | NO 3 | NO3 |
>
1. Only supported by wrapping a `` parent and snapshotting it.
2. It returns an empty image (not a failure Promise).
3. Component itself lacks platform support.
4. But you can just use the react-native-maps snapshot function: https://github.com/react-native-maps/react-native-maps#take-snapshot-of-map
5. Web support via html2canvas-pro has limitations with SVG rendering. Basic SVG works, complex SVG may have issues.
## Performance Optimization
During profiling captured several things that influence on performance:
1. (de-)allocation of memory for bitmap
2. (de-)allocation of memory for Base64 output buffer
3. compression of bitmap to different image formats: PNG, JPG
To solve that in code introduced several new approaches:
- reusable images, that reduce load on GC;
- reusable arrays/buffers that also reduce load on GC;
- RAW image format for avoiding expensive compression;
- ZIP deflate compression for RAW data, that works faster in compare to `Bitmap.compress`
more details and code snippet are below.
### RAW Images
Introduced a new image format RAW. it correspond a ARGB array of pixels.
Advantages:
- avoids PNG/JPEG compression; capture time still depends on the view and device.
RAW format supported for `zip-base64`, `base64` and `tmpfile` result types.
RAW files contain an ASCII `${width}:${height}|` header followed by binary pixel bytes. The `base64` result instead returns that header followed by base64-encoded pixels; `zip-base64` returns the header followed by base64-encoded, zlib-compressed pixels.
### zip-base64
In compare to BASE64 result string this format fast try to apply zip/deflate compression on screenshot results
and only after that convert results to base64 string. In combination zip-base64 + raw we got a super fast
approach for capturing screen views and deliver them to the react side.
### How to work with zip-base64 and RAW format?
Capture in React Native, then send the result and format to a Node.js process for conversion. Node's `fs` and `zlib` modules are not built into React Native.
```js
import {Platform} from "react-native";
import {captureRef} from "react-native-view-shot";
const format = Platform.OS === "android" ? "raw" : "png";
const result = Platform.OS === "android" ? "zip-base64" : "base64";
captureRef(viewRef, {result, format})
.then(data => {
// Send {data, format} to your Node.js conversion process.
})
.catch(console.error);
```
In Node.js:
```js
const fs = require("node:fs");
const zlib = require("node:zlib");
const {PNG} = require("pngjs");
function saveCapture(data, format, outputPath) {
let pngData;
if (format === "raw") {
const resolution = /^(\d+):(\d+)\|/.exec(data);
if (!resolution) throw new Error("Missing RAW dimensions");
const width = Number(resolution[1]);
const height = Number(resolution[2]);
const compressed = Buffer.from(data.slice(resolution[0].length), "base64");
const pixels = zlib.inflateSync(compressed);
if (!width || !height || pixels.length !== width * height * 4) {
throw new Error("Invalid RAW dimensions or pixel data");
}
const png = new PNG({width, height});
png.data = pixels;
pngData = PNG.sync.write(png);
} else {
// The iOS/Windows fallback is already PNG, not zlib-compressed RAW.
pngData = Buffer.from(data, "base64");
}
fs.writeFileSync(outputPath, pngData);
}
```
Keep in mind that packaging PNG data is a CPU consuming operation as a `zlib.inflate`.
Hint: use `process.fork()` approach for converting raw data into PNGs.
> Install the PNG encoder in your Node.js conversion project (`zlib` is built in):
>
> ```bash
> npm install pngjs
> ```
## Troubleshooting / FAQ
### Saving to a file?
- If you want to save the snapshotted image result to the CameraRoll, just use https://github.com/react-native-cameraroll/react-native-cameraroll
- If you want to save it to an arbitrary file path, use something like https://github.com/itinance/react-native-fs
- For any more advanced needs, you can write your own (or find another) native module that would solve your use-case.
### The snapshot is rejected with an error?
- Support of special components like Video / GL views is not guaranteed to work. In case of failure, the `captureRef` promise gets rejected (the library won't crash).
### get a black or blank result or still have an error with simple views?
Check the **Interoperability Table** above. Some special components are unfortunately not supported. If you have a View that contains one of an unsupported component, the whole snapshot might be compromised as well.
### black background instead of transparency / weird border appear around texts?
- It's preferable to **use a background color on the view you rasterize** to avoid transparent pixels and potential weirdness that some border appear around texts.
### on Android, getting "Trying to resolve view with tag '{tagID}' which doesn't exist"
> you need to make sure `collapsable` is set to `false` if you want to snapshot a **View**. Some content might even need to be wrapped into such `` to actually make them snapshotable! Otherwise that view won't reflect any UI View. ([found by @gaguirre](https://github.com/gre/react-native-view-shot/issues/7#issuecomment-245302844))
Alternatively, you can use the `ViewShot` component that will have `collapsable={false}` set to solve this problem.
### Getting "The content size must not be zero or negative."
> Make sure you don't snapshot instantly, you need to wait at least there is a first `onLayout` event, or after a timeout, otherwise the View might not be ready yet. (It should also be safe to just wait Image `onLoad` if you have one). If you still have the problem, make sure your view actually have a width and height > 0.
Alternatively, you can use the `ViewShot` component that will wait the first `onLayout`.
### Snapshotted image does not match my width and height but is twice/3-times bigger
This is because the snapshot image result is in real pixel size where the width/height defined in a React Native style are defined in "point" unit. You might want to set width and height option to force a resize. (might affect image quality)
### on Android, capture GL Views
A prop may be necessary to properly capture GL Surface View in the view tree:
```js
// Opt in to SurfaceView capture; it can have a significant performance cost.
captureRef(viewRef, {handleGLSurfaceViewOnAndroid: true});
```
### Trying to share the capture result with `expo-sharing`?
`tmpfile` or the default capture result works best for this. Add `file://` only when it is absent; Android already returns a file URI.
```js
captureRef(viewRef)
.then(uri =>
Sharing.shareAsync(
uri.startsWith("file://") ? uri : `file://${uri}`,
options,
),
)
.catch(console.error);
```
---
## Contributing
If your pull request changes the published library (a fix, feature or breaking change), add a changeset with `npm run changeset`: pick the bump (patch, minor or major), write a one-line summary for the changelog, and commit the generated `.changeset/*.md` file. Changes to docs, CI or the example apps don't need one.
Releases are automated: merging to `master` opens or updates a "Version Packages" pull request, and merging that pull request publishes to npm.
## Thanks
- To initial iOS work done by @jsierles in https://github.com/jsierles/react-native-view-snapshot
- To React Native implementation of takeSnapshot in iOS by @nicklockwood
- To Windows implementation by @ryanlntn