Search code examples
javascriptreact-nativebind

How to pass function arguments on button function in React Native?


I am pretty new to react and am having trouble figuring out how to pass arguments through to an event handler. I have tried binding it but I am not getting the syntax correct. I am referring to the onPress in the button which calls the decrement function. I have tested it without passing in parameters and just calling USER_ID directly in the function and with the onPress having the following syntax:

onPress={decrement}

..

export default function App() {
  const db = firebase.firestore().collection("users");
  const [count, setCount] = useState();
  const USER_ID = "INxK5dbadj6OmSn9mp6l";


  const decrement = (UID) => {
    var next = count - 1;
    if (next >= 0) {
      db.doc(UID).update({ Count: next });
      db.doc(UID)
        .get()
        .then(function (doc) {
          setCount(doc.data().Count);
        });
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.userContainer}>
        <Text>USER 1: {count}</Text>
        <View style={styles.buttonContainer}>
          <Button
            title="-"
            onPress={() => this.decrement.bind(this, USER_ID)} 
          />
        </View>
      </View>
    </View>
  );
}

Thank you for any guidance or help!


Solution

  • You should use onClick instead of onPress

          <button
            title="-"
            onClick={()=>decrement(USER_ID)} 
          />
    

    There is no reason to use bind and you can't use this because you are using a function component not a class component.