Calling a function in Arrow Function

51 Views Asked by At

I just wanted to know how does this work, if I have an onChange()

onChange={() => input()}

The above code immediately executes the input function when onChange() is triggered.

But what about this, how does this work?

onChange={() => input}

Even when onChange is triggered the input function is not being called.

What is the difference between these two statements?

1

There are 1 best solutions below

0
0stone0 On BEST ANSWER

input is a reference to the input function where as input() executes the input function and returns the value.

So when you call an arrow function without explicit brackets ({}), the value is automatically returned.


So onChange={() => input} will get the reference of the input function, where as onChange={() => input()} will get the return value of the input function.


Someone recommended onChange={input} in the comments, this will automatically pass all the parameters given to onChange (like the DOM event) to the input function, keep that in mind an this equivalent to onChange={(e) => input(e)}

This is fine for onChange of (eg) an <input> element, but one common mistake is by using the parseInt function, if you pass all the arguments to that, it will use it as base and give unexpected output:

const a = ['1','2','3'].map(parseInt);                      // WRONG
const b = ['1','2','3'].map((num) => parseInt(num, 10));    // GOOD

console.log(a, b)

[
  1,
  NaN,
  NaN
] 
[
  1,
  2,
  3
]

React demo showing the 4 cases shown above, please see the comments in the code regarding the working

const { useState } = React;

const Example = () => {

    const [value, setValue] = useState('Type!');
    
    const input = (e = false) => {
        const newVal = (e)
            ? e.target.value
            :'Nothing passed to input()';

        setValue(newVal);
    }

    return (
        <div>
            {/* OK: event is automaticly passed */}
            <input onChange={input} value={value} />
            
            {/* NO: function not called */}
            <input onChange={() => input} value={value} />
            
            {/* NO: event NOT passed to input function */}
            <input onChange={() => input()} value={value} />
            
            {/* OK: event is manually passed to function */}
            <input onChange={(e) => input(e)} value={value} />
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
div { display: flex; flex-direction: column; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>