Reputation: 137
I'm starting to learn react and es6. I saw some curly braces in the import part.
import React,{Component} from 'react';
I noticed that curly braces in this code is to import those named export.
But I also saw some code in the JSX part,like:
render() {
return (
<div>
<h1>Hello,wrold!</h1>
<h2>It is {new Date().toLocaleTimeString()}</h2>
</div>
);
}
I am confused ,does this curly braces has nothing to do with es6 syntax? or they have some kind of relation?
Upvotes: 0
Views: 549
Reputation: 464
When we import something, we need to keep this in mind. If a component or module is exported with default keyword, you don't need to use curly braces but if it is exported without default keyword you need to use curly braces.
ex:
export class Main extends Component{}
when you are importing this component you need to import like this.
import {Main} from 'filename';
But when you create a component and export it with default keyword, you don't need to use curly braces.
ex:
export default class Main extends Component{}
you can import it like this
import Main from 'filename';
And in case of component or module body, we use curly braces to integrate JSX and javascript code.
Upvotes: 3
Reputation: 359
The ES6 syntax
import React, {Component} from 'react';
Is an example of the syntax used to import ES6 modules - not to confuse with object destructuring. These are not related but are often confused as imports mimics shallow destructuring.
The JSX syntax
<h2>It is {new Date().toLocaleTimeString()}</h2>
Tells the JSX compiler to interpret whatever is inside the curly braces as javascript instead of text.
Neither the ES6 Import syntax, object destructuring, nor JSX curly braces are related.
Upvotes: 0
Reputation: 411
To "insert JSX/ES code inside the HTML"
The part in the curly braces are processed like javascript code and their result is returned and inserted between the "It is"
and "</h2"
Upvotes: 0