I'm having a hard time understanding the following ES6 syntax. I read the docs quite a bit and it seems like there is more than one change happening here:
const renderInput = props =>
<div>
<label>{props.placeholder}</label>
</div>
Would the above be equivalent to:
const renderInput = function renderInput(props) {
return <div>
<label>{props.placeholder}</label>
</div>
}
?
There are two ways to declare an arrow function: Without curly braces {} . With this syntax, the arrow function has an implicit return. For example, the below arrow function returns 42, even though there's no return .
An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.
Yes, that is correct. When you have only one expression, and it's the expression you wish to return from the function, you may omit the curly brackets.
Since <div><label>{props.placeholder}</label></div>
is, in fact, a single expression (it gets transpiled to React.createElement(......)
or something like that), and you wish to return it from renderInput
, that is indeed how you use the no-brackets version of the arrow function.
If you had wished to use variables or do some other computation (conditions, for loops, etc), you wouldn't have been able to omit the brackets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With