Take Screenshot in react-native.

Taking screenshots programmatically in react-native is very easy. Without further a do, let's start writing a code.

Dependencies

  1. react-native-view-shot for taking screenshots.
  2. @react-native-community/cameraroll for saving the screenshot.

Install the dependency

For npm -> npm install react-native-view-shot @react-native-community/cameraroll

For yarn -> yarn add react-native-view-shot @react-native-community/cameraroll

After installing the dependencies

  • Import the ViewShot and CameraRoll
import ViewShot from 'react-native-view-shot';
import CameraRoll from '@react-native-community/cameraroll';
  • After importing ViewShot wrap the area we want to take screenshot using ViewShot.

  • Now we will use useRef hook to create ref.

    import React, {useRef} from 'react'; // should be outside the component
    
    const ref = useRef(); // should be inside the component
    
  • Pass the required props in ViewShot as mentioned below.

 <ViewShot
    ref={ref}
    options={{
    fileName: 'file-name', // screenshot image name
    format: 'jpg', // image extension
    quality: 0.9 // image quality
   }} >

....some amazing content ....
<ViewShot/>
  • Create a function to take screenshots and paste the below code.
 const takeScreenShot = () => {
   // to take a screenshot
    ref.current.capture().then(uri => {
      // to save screenshot in local memory
      CameraRoll.save(uri,{type:"photo",album:"Album codes"});
      alert("Took screenshot");
    });
  };
  • Call the above function to take the screenshot.

And Voila, We're done easy peasy :) easy peasy

Complete code

import React, {useRef} from 'react';
import {StyleSheet, Text, View, Button} from 'react-native';
import ViewShot from 'react-native-view-shot';
import CameraRoll from '@react-native-community/cameraroll';

const SomeComponent =() => {

  const ref = useRef();
  const takeScreenShot = () => {
    ref.current.capture().then(uri => {
      CameraRoll.save(uri,{type:"photo",album:"QR codes"});
      alert("Took screenshot");
    });
  };

  return (
    <View style={styles.container}>
      <ViewShot
        ref={ref}
        options={{
        fileName: 'file-name', // screenshot image name
        format: 'jpg', // image extention
        quality: 0.9 // image quality
        }} >
        <Text> Some awesome content</Text>
      </ViewShot>
      <Button title="Share QR Code" onPress={takeScreenShot}/>
    </View>
  );
};


const styles = StyleSheet.create({
  container: {
    flex:1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#171821',
  }

});

Did you find this article valuable?

Support aamchora by becoming a sponsor. Any amount is appreciated!