Invalid hook call. Hooks can only be called inside of the body of a function component

Hello,
I try to use the banercodescanner in my expo app. I using all the code of the documentation but I get this error : Invalid hook call. Hooks can only be called inside of the body of a function component.

import React, { useState, useEffect, Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

class QrCode extends Component {

    render () {
        const [hasPermission, setHasPermission] = useState(null);
        const [scanned, setScanned] = useState(false);

        useEffect(() => {
            (async () => {
                const { status } = await BarCodeScanner.requestPermissionsAsync();
                setHasPermission(status === 'granted');
            })();
        }, []);

        const handleBarCodeScanned = ({ type, data }) => {
            setScanned(true);
            alert(`Bar code with type ${type} and data ${data} has been scanned!`);
        };

        if (hasPermission === null) {
            return <Text>Requesting for camera permission</Text>;
        }
        if (hasPermission === false) {
            return <Text>No access to camera</Text>;
        }

        return (
            <View style={styles.container}>
                <BarCodeScanner
                    onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                    style={StyleSheet.absoluteFillObject}
                />
                {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

export default QrCode;

That is my code, i use a custom component

I try to use the banercodescanner in my expo app. I using all the code of the documentation but I get this error

Example in the documentation is using function component, your code is using class components. You can mix class components and function components in your app, but hooks can be used only in functions

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.