softcode
softcode

Reputation: 4648

ES6 Arrow function without curly braces

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>
}

?

Upvotes: 7

Views: 2697

Answers (1)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174977

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.

Upvotes: 4

Related Questions