0

Came across the below code in the apollo docs today. I thought that when you have a multi-line return statement in a functional component that you have to wrap everything in parentheses? So, right after return you'd open the parentheses, like this: return(.

I'm confused why this return statement works:

export default function ExchangeRates() {
  const { loading, error, data } = useQuery(EXCHANGE_RATES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.rates.map(({ currency, rate }) => (
    <div key={currency}>
      <p>
        {currency}: {rate}
      </p>
    </div>
  ));
}

Edit: the suggested answer doesn't answer the question for me. I'd appreciate an answer that addresses the JSX also. For example, someone has said the () are not even necessary to wrap the JSX here so I'm extra confused why the material on this say to enclose a multi-line return statement in ().

12
  • 2
    Probably because the multiline jsx is already wrapped in the map Commented Apr 17, 2021 at 18:28
  • 1
    Does this answer your question? Why use parentheses when returning in JavaScript? Commented Apr 17, 2021 at 18:30
  • 1
    @cheznead it's usually used to prevent automatic semicolon insertion, and in your example, there's no need since there's no ambiguity for JavaScript. It would be necessary for multiline only when the return statement is alone on its line. Commented Apr 17, 2021 at 18:56
  • 1
    I wouldn't say it contradicts anything, but I do agree that this specific answer doesn't explain why. Another answer below does explain why. The term multiline is misleading in your case since it's true that your example spreads over multiple lines, though the multiline that they're talking about is when the returned values start on the line below the return keyword. Commented Apr 17, 2021 at 19:21
  • 2
    ah ok, thank you. I think I get it now. So if you add a line break, you need to introduce ( right after return keyword, but if you begin statement after return, you don't need it. Commented Apr 17, 2021 at 19:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.