Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Const With Curly Braces in JSX

Tags:

jsx

react-jsx

I'm just getting started with React Native and getting used to JSX syntax. Is that what I'm talking about? Or am I talking about TypeScript? Or... ES6? Anyway...

I've seen this:

const { foo } = this.props; 

Inside a class function. What is the purpose of the curly braces and what's the difference between using them and not using them?

like image 787
Varrick Avatar asked Aug 04 '16 12:08

Varrick


People also ask

What does {} mean in JSX?

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. You need them when you want to use a JavaScript expression like a variable or a reference inside JSX.

How do you use curly braces in JSX?

How braces { } are used. Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.

How do I use const in JSX?

Embedding Expressions in JSXconst name = 'Josh Perez';const element = <h1>Hello, {name}</h1>; You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2 , user. firstName , or formatName(user) are all valid JavaScript expressions.

How do I declare an element in JSX?

To use JavaScript inside of JSX, you need to surround it with curly braces: {} . This is the same as when you added functions to attributes. To create React components, you'll need to convert the data to JSX elements. To do this, you'll map over the data and return a JSX element.


1 Answers

It is destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Example (ES6):

var person = {firstname: 'john', lastname: 'doe'};  const firstname = person.firstname; const lastname = person.lastname;  // same as this const { firstname, lastname } = person; 

You can find more info at MDN

EDIT: also for developers familiar with Python language it can be interesting to compare with Python unpacking syntax. Python2.7:

>>> _tuple = (1, 2, 3) >>> a, b, c = _tuple >>> print(a, b, c) (1, 2, 3) 

With new feature of Python3, like PEP 3132 you can also do following:

>>> _range = range(5) >>> a, *b, c = _range >>> print(a, b, c) 0 [1, 2, 3] 4 

Examples are added, because knowing already similar approach from other languages you can grasp JS idea more quicker.

like image 83
wolendranh Avatar answered Sep 21 '22 13:09

wolendranh