Reputation: 85
I am trying to access camera using React native app. I have copied all the code from official documentation. Every one has done the same including the official expo-docs https://docs.expo.io/versions/latest/sdk/camera/. My code to access the camera and take picture is
export default function Cameracontrol() {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
async function takePicture() {
console.log(this.camera)
if (this.camera) {
console.log('Pictactue Taken')
let photo = await this.camera.takePictureAsync();
}
else {
console.log('Caera Not Open');
}
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={type}
ref={camera => this.camera = camera}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", margin: 20 }}>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}>
<Ionicons
name="ios-photos"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={takePicture}
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<MaterialCommunityIcons
name="camera-switch"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
</View>
</View>
</Camera>
</View>
);
}
I am experiencing the following error.
undefined is not an object (evaluating '_this.camera = camera')
this error is strongly related with the line
ref={camera => this.camera = camera}
By removing this line of code the error is also removing.
I would really really appreciate if some boy would help me with this.
Upvotes: 1
Views: 2220
Reputation: 1645
You are in a functional component, not a class. Therefore, you cannot use this
. Also, ref
is not working like in classes.
You should use useRef
: https://reactjs.org/docs/hooks-reference.html#useref
const inputEl=useRef(null);
<input ref={inputEl} type="text" />
Upvotes: 1