0

Why in the start snippet below, the const user are wrapped in curly braces and the const element are wrapped in parentheses?

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

ReactDOM.render(
  element,
  document.getElementById('root')
);
Hans Zimermann
  • 330
  • 2
  • 10
  • 4
    becuase an object is being assigned to `const user` is an object, and the result of an expression is being assigned to `const element`. The `()` around element is optional though. You could also do `const user = ({ firstName: 'Harper', lastName: 'Perez' });` – dave Apr 19 '18 at 18:54
  • 3
    jsx is an expression like 3+5 or (3+5) – Ali Ankarali Apr 19 '18 at 18:54

2 Answers2

2

When you use:

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

You're using JSX, which offers a Javascript XML like language, it's like a pre-processor.

Otherwise, when you use:

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

You're creating a plain Javascript object, where you can store data and access it like user.firstName or user.lastName.

2

In first case:

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

user is an object with key: value pairs and hence {}

while in second case,

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

the multiline JSX expression in wrapped within () to add to the readability of the code, and as per the docs,

It is recommend to wrap it in parentheses to avoid the pitfalls of automatic semicolon insertion.

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
  • 5
    Not entirely correct; the JSX expression is multi-line for readability, but the parentheses are to avoid automatic semicolon insertion, as stated in the [docs](https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx). – Herohtar Apr 19 '18 at 18:58