I’m very new to React native and lately just been messing around with it. I’ve been having problems every time I use one of the touchable components. For some reason it doesn’t respond when I click the touchable component. I tried looking at other solutions but got no where. (I’m also using Expo if you need to know that)
import {
ImageBackground,
StyleSheet,
View,
SafeAreaView,
Platform,
StatusBar,
Text,
TouchableOpacity,
} from "react-native";
const StartScreen = () => {
return (
<ImageBackground
source={require("../assets/Background.png")}
style={{ flex: 1 }}
>
<SafeAreaView style={styles.ContentArea}>
<TouchableOpacity onPress={console.log("Button pressed!")}>
<View style={styles.nextButton}>
<Text style={{ fontWeight: "bold", fontSize: 15 }}>Test</Text>
</View>
</TouchableOpacity>
</SafeAreaView>
</ImageBackground>
);
};
const styles = StyleSheet.create({
ContentArea: {
flex: 1,
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
justifyContent: "flex-end",
alignItems: "center",
},
nextButton: {
width: 150,
height: 40,
backgroundColor: "tomato",
marginBottom: 45,
alignItems: "center",
justifyContent: "center",
borderRadius: 50,
},
});
export default StartScreen;
>Solution :
You are passing a function invocation inside the onPress
method. This makes the console.log run on the render. console.log()
returns undefined, so your onPress
prop is ultimately undefined
itself. What you want to do, is pass a reference to a function, or an anonymous function instead. Here’s an example:
...
<TouchableOpacity onPress={() => console.log("Button pressed!")}>
<View style={styles.nextButton}>
<Text style={{ fontWeight: "bold", fontSize: 15 }}>Test</Text>
</View>
</TouchableOpacity>
...