Search code examples
reactjsreact-nativescreenshot

how can i take screenshot with a button in react native?


I want to develop a simple app that can take screenshot of current screen by a button. This code run successfully but when i press capture button then it not works and return error.

export default class App extends Component<{}> {
  render() {
    captureScreen({
      format: "jpg",
      quality: 0.8
    })
    .then(
      uri => console.log("Image saved to", uri),
      error => console.error("Oops, snapshot failed", error)
    );
    
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native SnapShot!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
        <Button
          onPress={captureScreen.bind(this)}
          title="capture"
          color="#841584"
          accessibilityLabel="Capture"
        />
      </View>
    );
  }
}


Solution

  • Why are you capturing screenshot in render? I think you need to move your screenshot snippet to a separate function.

    export default class App extends Component<{}> {
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native SnapShot!
            </Text>
            <Text style={styles.instructions}>
              To get started, edit App.js
            </Text>
            <Text style={styles.instructions}>
              {instructions}
            </Text>
            <Button
              onPress={() => {
                captureScreen({
                  format: "jpg",
                  quality: 0.8
                })
                .then(
                  uri => console.log("Image saved to", uri),
                  error => console.error("Oops, snapshot failed", error)
                );
              }}
              title="capture"
              color="#841584"
              accessibilityLabel="Capture"
            />
          </View>
        );
      }
    }