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'
export default function Main({ navigation }) {
return (
....
<View style={styles.container}>
<Pressable style={styles.button} onPress={ <Scanner() function call> }>
<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 Scanner() 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.
You should write function Scan in the parent component -> Main.js and forward it to the children component -> Scanner.js. That's called prop drilling https://blogs.perficient.com/2021/12/03/understanding-react-context-and-property-prop-drilling/#:~:text=Prop%20drilling%20refers%20to%20the,because%20of%20its%20repetitive%20code.
This is not a good patern, but you can do that. You can create the function in the parent and send it as a prop to the child or you can use context hook from react, that hook lets you pass the function from the child to the parent. Another method is to use forwardRef, this will let you call the child function from the parent.