Last active
May 20, 2019 09:28
-
-
Save tokland/4d8fdba19c62463320cd79e021535d28 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import PropTypes from "prop-types"; | |
import { Text, View, StyleSheet } from "react-native"; | |
import { Camera, Permissions } from "expo"; | |
/* Expo does not provide a light component, but we can control the flash using the Camera component. */ | |
class FlashLight extends React.Component { | |
static propTypes = { | |
isActive: PropTypes.bool.isRequired | |
}; | |
state = { | |
hasPermissions: undefined | |
}; | |
async componentDidMount() { | |
const { status } = await Permissions.askAsync(Permissions.CAMERA); | |
this.setState({ hasPermissions: status === "granted" }); | |
} | |
render() { | |
const { isActive } = this.props; | |
const { hasPermissions } = this.state; | |
const { FlashMode, Type } = Camera.Constants; | |
const flashMode = isActive ? FlashMode.torch : FlashMode.off; | |
if (hasPermissions === undefined) { | |
return <View />; | |
} else if (!hasPermissions) { | |
return <Text>Required permissions not granted</Text>; | |
} else { | |
return ( | |
<Camera style={styles.camera} flashMode={flashMode} type={Type.back} /> | |
); | |
} | |
} | |
} | |
const styles = StyleSheet.create({ | |
// Set the camera component to the smallest size possible (caveat: it must be visible to work) | |
camera: { flex: 0, width: 1, height: 1, opacity: 0 } | |
}); | |
export default FlashLight; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment