Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active May 20, 2019 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokland/4d8fdba19c62463320cd79e021535d28 to your computer and use it in GitHub Desktop.
Save tokland/4d8fdba19c62463320cd79e021535d28 to your computer and use it in GitHub Desktop.
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