I’m new to React and I’ve faced such a problem:
I have Main.js file with a button:
import * as React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native';
import { MaterialIcons, MaterialCommunityIcons} from '@expo/vector-icons';
import { DrawerActions } from '@react-navigation/native';
import Scanner from './Scanner'
const handleButtonPress = () => Alert.alert('Button pressed')
export default function Main({ navigation }) {
return (
....
<View style={styles.container}>
<Pressable style={styles.button} onPress={ handleButtonPress }>
<Text style={styles.buttonText}>Take charger</Text>
</Pressable>
</View>
);
}
An I have another file Scanner.js:
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
export default function Scanner() {
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,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}
});
How can I call a function Scan() from Scanner.js on button click in the Main()
function in Main.js. I’ve tried onPress={() => Scanner} but it didn’t work for me because of wrong hooks usage.