Skip to content
Advertisement

behavior of arrow function vs normal function in onPress method

‘m learning native react and learning more about javascript, so I still do not understand many things about its behavior. I have created a button component, using TouchableOpacity, and its props onPress. For it to work, I must send the function I want to execute as a props, but here I have fallen due to my little experience.

I am sending a console.log that is activated when I press the button. So I passed the console.log directly in the props that I defined, but it did not work when I clicked on the button, but, it was executed when the code is initialized. On the other hand, when I have passed an arrow function that contains the console.log, it has been executed at the moment of clicking the button.

to make it clearer I’ll show my code:

this is my button component:

const Button = ({ onUserPress, children, color }) => {

    const state = {

    };
    return (
        <TouchableOpacity onPress={ onUserPress } style={styles.buttonStyle} >
            <Text style={styles.textStyle}>
                {children}
            </Text>
        </TouchableOpacity>
    );
};

and i call them like this:

<Button onUserPress={ console.log("hello") }>Something</Button>

This is executed at the time of initializing my application, and nothing is happened when the button is pressed.

on the other hand, when i use the same component, but i pass the console.log in arrow function, like this:

<Button onUserPress={ ()=>{console.log("hello")} }>Something</Button>

this execute the console log only when i press the button component.

Could someone explain to me why the behavior is different? The world of functional programming is totally new to me and these things seem strange to me. According to what I understand, both are functions, so for me they do not make a difference (obviously, from my ignorant point of view). What is the difference that makes the behavior different?

Advertisement

Answer

You aren’t comparing a “normal function” with an arrow function.

The content between { and } is an expression which is evaluated and the result is assigned to the prop.

Thus you are calling console.log("hello"), taking the return value and assigning that as a function to onUserPress (this makes no sense as the return value of console.log is not a function).


Not a function:

console.log("hello");
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement