0
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;
Hyetigran
  • 760
  • 7
  • 18
  • 1
    Arrow functions with braces need a `return` keyword like a normal function. Arrow functions without braces evaluate a single expression and return the result. This is totally unrelated to React. – ggorlen Jul 23 '20 at 22:16
  • 2
    Does this answer your question? [When should I use \`return\` in es6 Arrow Functions?](https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions) – ggorlen Jul 23 '20 at 22:17

2 Answers2

2

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.

RemcoGerlich
  • 27,022
  • 4
  • 55
  • 74
0

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.

JBallin
  • 4,767
  • 33
  • 38