I'm currently taking an online course to learn React and I'm confused as to when I should be using {
vs (
.
I have 3 files:
App.js
const App = () => {
card-list.component.jsx
const CardList = ({ monsters }) => (
card.component.jsx
const Card = ({ monster }) => {
This is the code that currently works. Notice that on the second code the last character used is (
. I thought of changing it to {
to make it consistent with the other files but somehow the card list no longer shows up on the page although I didn't get any compile errors.
Can someone explain this to me and tell me when I should use one over the other?
CodePudding user response:
This essentially is a feature of arrow functions in js.
const myArrowFunc = ({key1}) => ("Hello there! " key1);
is essentially the same as
const myArrowFunc = ({key1}) => { return "Hello there! " key1 };
when you leave out the curly brackets, the return is implicit. When you include the curly brackets, you must explicitly use the return statement.
const someObj = { key1: "value1" };
const someReturn = myArrowFunc(someObj);
console.log(someReturn); // logs "Hello there! value1" to the console
CodePudding user response:
()=>{}
is the syntax of arrow function
When an arrow function only contains one line that return a value, e.g.:
() => {
return 1;
}
it can be simplified to
() => 1
Now what if you want to return an object
directly? i.e. how to simplify
() => {
return { foo: "bar" }
}
Since an object
also use {}
, you cannot write {foo: "bar"}
directly after the arrow as it will be treated as the function body. Wrapping the object
within ()
solves the problem since a ()
chunk must be an expression. The above example can be simplified to
() => ( { foo : "bar" } )