alernerdev
alernerdev

Reputation: 2064

distinction between "() => (" and "() => {"

I am taking React classes and it seems I can do:

const Header = () => (
  <div></div>
)

or

const Header = () => {
  return (<div></div>)
}

Notice regular parenthesis in the first syntax, and lack of return keyword. The second syntax is the one I am more familiar with -- it is clearly "the body of the function". But what does the first syntax mean? By the way, its coming from advanced react class by Wes Bos, and its in the context of next.js -- may be that makes a difference?

Upvotes: 0

Views: 55

Answers (2)

webHasan
webHasan

Reputation: 481

()=> mean you direct returning something. So you can write your code like

const Header = () => <div>something</div>

() after => is not related to function, it is related to jsx.

Also, you can write only a single expression whether you return it or not. Something like following.

let squ = (n) =>  n * n;

let message = () => alert('some message')

Only one exception is you can't return an object like this way. Following code does not work.

const Header = () => {name: 'some thing', age: 30}

If you like to direct return object you have to wrap the object by (). So this should be

const Header = () => ({name: 'some thing', age: 30})

Next part of your question () => {” it is pretty similar to normal function and I think your concept is clear here. You need it when you do not directly return anything. Doing some action inside the function or return something after some code.

Upvotes: 1

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

You no need to explicitly add return to return elements

const Header = () => (
  <div></div>
)

But here you need to explicitly add return to return elements

const Header = () => {
  return (<div></div>)
}

Upvotes: 1

Related Questions