How come whenever I move from a screen to another screen, my button get automatically pressed straight away without me even pressing on it.
My code (Review screen)
import { StyleSheet, Text, View, SafeAreaView, TextInput, TouchableOpacity, Button } from 'react-native'
import React , {useEffect, useState} from 'react'
import {ref, onValue} from 'firebase/database'
import {db} from '../firebase'
const Reviews = ({route}) => {
const paramKey = route.params.paramKey1
var ke;
const [todoDatak, setToDoDatak] = useState([])
const [todoDatafb, setToDoDatafb] = useState([])
useEffect (() => {
const starCountRef = ref(db, "food/" + paramKey);
onValue(starCountRef, (snapshot) =>{
ke = snapshot.key;
setToDoDatak(ke)
});
})
return (
<View style = {styles.container}>
<Text style = {styles.header}>Shop Name</Text>
<Text style = {styles.text}>{todoDatak}</Text>
<View style={{
borderBottomColor: 'black',
borderBottomWidth: StyleSheet.hairlineWidth,
}}
/>
<View style = {styles.inputContainer}>
<Text></Text>
<Text> Feedback: </Text>
<TextInput
editable
multiline
numberOfLines={5}
maxLength={500}
placeholder = "Key in for any feedback for the shop"
//value={email}
onChangeText ={text => setToDoDatafb(text)}
style = {styles.input}
/>
<TouchableOpacity
onPress = { console.log("Pressed")}
style = {styles.text}
>
<Text style={styles.textP}>Post</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default Reviews
Upon loading this page, the button is pressed automatically 3 times
Shown in my log
But if i try to manually click the button, nothing happen. No new logs of ‘Pressed’ appearing in my logs.
How do I prevent the page from clicking the button by itself? Also how do I fix the issue of me manually clicking the button but it did not work?
2
Answers
Try this
() => console.log('Pressed')
What is happening? You are not pressing anything, React is calling your console.log() on every render. Because of the () at the end. Making it a function call. Similar to how you would call any other function in your code.
Instead we should pass just the head of the function, telling Javascript to "call this function when the user presses", in this case we pass an anonymous arrow function, but we don’t immediately call it.
The problem is in
onPress
, because your expression ({ console.log("Pressed")}
) literally means: "assign the result ofconsole.log("Pressed")
to theonPress
handler ofTouchableOpacity
". Sincevoid 0
is a valid handler (it means no handler) this will not provide any error in compile time / runtime.The result of
console.log
though isvoid 0
(undefined
), so no event is registered, but theconsole.log
is executed (hence the log in the console), which will be running once every re-render.To properly assign the even handler, wrap the console.log in a closure:
onPress={() => console.log("Pressed")}