In this line:
import React, { Component } from "react";
why the braces are only around Component and not also on 'React'?
To use import aliases when importing components in React, use the as keyword to rename the imported component, e.g. import {Button as MyButton} from './another-file' . The as keyword allows us to change the identifying name of the import.
Combining. You can combine default and named exports in a single file. Importing is the same, named exports are in curly brackets, default is plaintext. React is a great example of a library that exports both default and named components.
What are Named Exports? Named exports allow us to share multiple objects, functions or variables from a single file and were introduced with the release of ES2015. Named exports are imported with curly braces in various files and must be imported using the name of the object, function or variable that was exported.
Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing. The basic idea behind imports and exports is to exchange contents between several JavaScript files. Let's look at these features one by one.
Here's a great answer that explains default and named imports in ES6
Let's say we have a class named Foo that I want to import. If I want to get the default export, I would do:
import Foo from './foo.js';
If I wanted a specific function inside the foo file, I would use the curly braces.
import { fooFunction } from './foo.js';
Note, this isn't a React feature, but ES6. Likely you are using babel to transpile your code from ES6 to ES5.
To create something similar in react. Lets take this following example.
someobject.js
const someobject = {
somefunc1: ()=>console.log("hello 1"),
somefunc2: ()=>console.log("hello 2")
}
export default someobject;
app.js
import someobject, { somefunc1, somefunc2 } from "./someobject";
someobject.somefunc1(); //hello 1
someobject.somefunc2(); //hello 2
somefunc1(); //hello 1
somefunc2(); //hello 2
export defaul
In the React module the default export is the React
object and it also has a named export Component
1, something like this:
// assuming React and Component are predefined
export default React
export Component
Coincidentally Component
is also available on the React object, so it is not necessary to import separately, although some people prefer your approach. For example this is possible:
// MyComponent.js
import React from 'react'
class MyComponent extends React.Component {}
More information about ES6 module syntax can be found here.
1 Note that actually the React library does not have a named export Component
as in the example above, however Component
is a property on the default export and so due to the way that ES6 packages are transpiled by Babel, this becomes a named export, the behaviour then being as in the example above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With