How to toggle React Native Camera Torch on/off

Viewed 5763

I am working on a React Native app that scans barcodes. I want to enable the user the toggle the light on and off with the press of a button. Right now the light stays on at all times. Would this be possible with the React Native camera component? Thank You!

class CameraScreen extends React.Component {
  state = {
    isCameraReady: false
  };

  constructor(props) {
    super(props);
    this.handleCameraReady = this.handleCameraReady.bind(this);
    this.state = {
      camera: {
        type: RNCamera.Constants.Type.back
      }
    };
  }
  handleCameraReady() {
    this.setState({
      isCameraReady: true
    });
  }

  onBarCodeRead = data => {
    this.setState({ scanned: true });
    const DATA_SKU = data.data.split("*");
    const SKU = DATA_SKU[0];
    const STK_ID = DATA_SKU[1] !== undefined ? DATA_SKU[1] : "";
    this.setState({ showCamera: false });
    this.props.navigation.navigate("Home", {
      scanDataSku: SKU,
      scanDataStkID: STK_ID
    });
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <RNCamera
          style={styles.container}
          onBarCodeRead={this.onBarCodeRead}
          ref={cam => (this.camera = cam)}
          cameraProps={{ captureAudio: false }}
          flashMode={
            this.state.isCameraReady
              ? RNCamera.Constants.FlashMode.torch
              : RNCamera.Constants.FlashMode.off
          }
          onCameraReady={this.handleCameraReady}
        ></RNCamera>
        <View style={styles.bottomNav}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate("Home")}
            style={styles.bottomBtn}
          >
            <Text style={styles.bottomTxt}>Back</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.bottomBtn}>
            <Text style={styles.bottomTxt}>Light</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }
}
1 Answers

Yes - I did something similar:

toggleTorch()
{
    let tstate = this.state.torchon;
    if (tstate == RNCamera.Constants.FlashMode.off){
       tstate = RNCamera.Constants.FlashMode.torch;
    } else {
       tstate = RNCamera.Constants.FlashMode.off;
    }
    this.setState({torchon:tstate})
}

and then set the flash mode to the appropriate state:

<RNCamera
    flashMode={this.state.torchon}
    ...

Here's how I defined the button:

<TouchableOpacity style={styles.toggleTorch}  onPress={() => this.toggleTorch() }>
{ this.state.torchon == RNCamera.Constants.FlashMode.off? (
        <Image style={styles.iconbutton} source={require('../images/flash.png')} />
    ) : (
        <Image style={styles.iconbutton} source={require('../images/flash-on.png')} />
    )
}
</TouchableOpacity
Related