Thursday, May 23, 2024
131
rated 0 times [  138] [ 7]  / answers: 1 / hits: 6978  / 5 Years ago, mon, october 14, 2019, 12:00:00

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>
);
}
}

More From » react-native

 Answers
4

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

[#5934] Saturday, October 12, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
joanneamiyaa questions
;