0

My lack of success in this problem may be due to a lack of proper terminology when Googling it but nonetheless I am completely stumped. I am passing an onPress function to a custom component in react native. When I pass it by itself as:

export const AddMorePlants = ( onPress ) => {
    return (
        <TouchableHighlight
            onPress={onPress}>
.
.
.
}

I get a this2.props.onPress is not a function error but when I have the exact same code except with the onPress passed within curly braces:

export const AddMorePlants = ({ onPress }) => {
    return (
        <TouchableHighlight
            onPress={onPress}>
.
.
.
}

It Works!

Why does the second one work and not the first?

Sorry for a kind of basic question I just have been really Googling and cant figure it out. Thanks in advance and I can provide any more info if needed.

TitanJamison
  • 5
  • 1
  • 4
  • according to first one function should be call like `AddMorePlants(direction function pass here)` for second function should be call like `AddMorePlants({onPress: function defination pass like this})` may this is a reason – Zia ur Rehman Mar 21 '21 at 02:54

2 Answers2

1

A functional component in React only has one parameter. The props. You can read more about it here

So what your first attempt at passing the onPress function actually looks like is:

export const AddMorePlants = (props) => {
   return (
       <TouchableHighlight onPress={props}/>
   );
}

When the TouchableOpacity tries to execute the method, it hits the is not a function error because props is an object.

When you do:

export const AddMorePlants = ({onPress}) => {
   return (
       <TouchableHighlight onPress={onPress}/>
   );
}

what you are doing is something called destructuring assignment and it's equivalent of doing:

export const AddMorePlants = (props) => {
   const {onPress} = props;
   return (
       <TouchableHighlight onPress={onPress}/>
   );
}

By putting the brackets inside the parentheses you are just doing a shorthand version of this destructuring assignment that we have mentioned.

Here's another version that would also work:

export const AddMorePlants = (props) => {
   return (
       <TouchableHighlight onPress={props.onPress}/>
   );
}

As you can see there are many ways to access an object's property.

The important part is to remember that the props object is the only parameter passed into a functional component.

I hope this helps you understand what's going on there.

Carlos J
  • 2,965
  • 4
  • 17
  • 28
0

In the first function you need to pass only one param i.e onPress to your component while in second you are destructuring assignment so you are doing something like onPress = this.props.onPress and passing an object of params.

Rohit Aggarwal
  • 1,048
  • 1
  • 14
  • 32