Take Screenshot in react-native.
Hemendra Khatik
Posted on June 21, 2022
Taking screenshots programmatically in react-native is very easy. Without further a do, let's start writing a code.
Dependencies
-
react-native-view-shot
for taking screenshots. -
@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 :)
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',
}
});
💖 💪 🙅 🚩
Hemendra Khatik
Posted on June 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
mobileappdevelopment Advanced Tricks in React Native Programming for Mobile Development
September 3, 2024