Neeraj Singh
Neeraj Singh

Reputation: 5

fat arrow function with a ternary working with parentheses instead of curly braces!!! Why?

import React from "react";
import Hill from "./Hill";
import Animal from "./Animal";

const fav = "hill";

this is not working;

//        const App = () => {
// <>
// <h1> my fav card</h1>;
//     {fav === "hill" ? <Hill/> : <Animal/>}
// </>
// }

this code is working when i am using parentheses insted of curly braces...why???

const App = () => (
  <>
    <h1> my fav card</h1>;
    {fav === "hill" ? <Hill /> : <Animal />}
  </>
);
export default App;

Upvotes: 0

Views: 111

Answers (2)

JBallin
JBallin

Reputation: 9787

Arrow functions can implicitly return the value that comes after the fat arrow (in your case the value is what is in the parens).

If you use brackets, you’ll need to explicitly return a value using the “return” keyword (like a regular function definition).

If you want to use brackets (benefit being if you want to add some logic outside of the return statement in the future without needing to add brackets later), just wrap the current code in the brackets with parens and put a “return” in front of it. Otherwise, using the arrow function as you have it works perfectly well - up to you.

Note that the ternary has no relation to this question.

Upvotes: 0

RemcoGerlich
RemcoGerlich

Reputation: 31260

Arrow functions can have either an expression, or a function body, like:

const five = () => 5;

or

const five = () => {
    return 5;
}

Note that the second needs to use return to return its return value.

Your code with braces will work if you use the return statement to return your JSX.

Upvotes: 2

Related Questions