How to bind onPress with an argument in React Native?

Sometimes, we want to bind onPress with an argument in React Native.

In this article, we’ll look at how to bind onPress with an argument in React Native.

How to bind onPress with an argument in React Native?

To bind onPress with an argument in React Native, we can create a function that returns the onPress handler function.

For instance, we write:

import * as React from 'react';
import { Button, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const onPress = (arg) => () => {
    console.log(arg);
  };

  return (
    <View>
      <Button title="button" onPress={onPress('hello')} />
    </View>
  );
}

to add a Button with the onPress prop set to the function that we get after we call onPress with 'hello'.

We define onPress to return a function that logs the arg that we passed into the outer function.

Therefore, when we press the button, we see 'hello' logged.

Conclusion

To bind onPress with an argument in React Native, we can create a function that returns the onPress handler function.