Edit this page
In this tutorial, learn how to handle platform differences between native and web when creating a universal app.
Edit this page
Android, iOS, and the web have different capabilities. In our case, both Android and iOS can capture a screenshot with the react-native-view-shot
library, however, web browsers cannot.
In this chapter, let's learn how to make an exception for web browsers to get the same functionality on all platforms.
1
To capture a screenshot on the web and save it as an image , we'll use a third-party library called dom-to-image. It allows taking a screenshot of any DOM node and turning it into a vector (SVG) or raster (PNG or JPEG) image.
Stop the development server and run the following command to install the library:
-
npm install dom-to-image
After installing it, make sure to restart the development server and press w in the terminal.
To use it, let's import it into App.js:
import domtoimage from 'dom-to-image';
2
React Native provides a Platform
module that gives us access to information about the platform on which the app is currently running.
You can use it to implement platform-specific behavior.
Import the Platform
module in App.js:
import { StyleSheet, View, Platform } from 'react-native';
Inside the onSaveImageAsync()
function in the <App>
component, we'll use Platform.OS
to check whether the platform is 'web'
.
If it is not 'web'
, we'll run the logic added previously to take and save the screenshot. If it is 'web'
,
we'll use the domtoimage.toJpeg()
method to convert and capture the current <View>
as a JPEG image.
const onSaveImageAsync = async () => {
if (Platform.OS !== 'web') {
try {
const localUri = await captureRef(imageRef, {
height: 440,
quality: 1,
});
await MediaLibrary.saveToLibraryAsync(localUri);
if (localUri) {
alert('Saved!');
}
} catch (e) {
console.log(e);
}
} else {
try {
const dataUrl = await domtoimage.toJpeg(imageRef.current, {
quality: 0.95,
width: 320,
height: 440,
});
let link = document.createElement('a');
link.download = 'sticker-smash.jpeg';
link.href = dataUrl;
link.click();
} catch (e) {
console.log(e);
}
}
};
On running the app in a web browser, we can now save a screenshot:
The app does everything we set out for it to do, so it's time to shift our focus toward the purely aesthetic.
In the next chapter, we will customize the app's status bar, splash screen, and app icon.