Import and Export in React
If you are new to React, You might be wondering behavior of importing and exporting in React. This article will give you massive understanding of it.
There are two ways to export anything from file. Those are Named export and Default export.
Named Export — Named export allows to have multiple exports per file.
Default Export — Only one default export is allowed per file.
Export
We can export a component, a variable and function by placing export before it’s declaration.
Also we can place export separately.
Import
We put a list of what to import in curly braces. import {….} , like that.
If there are many things to import, we can import everything as an object using import * as .
Import “as”
We can use as to import under different names. Let’s import HelloComponent with name Hello and ByeComponent as Bye.
Export ‘’as’’
This syntax is similar as previous. We can export with different names using as.
Export Default
This is similar to which I have mentioned under the Default export topic. A file can have many named exports alone with only one default export. Again, It means a file can have only one default export.
Import without curly braces.
There is no need to import it as HelloComponent. We can give it any name as it’s a default export.
Re-export
Re-export allows to import things and immediately export them. Using re-export we are able to export all things through a main file.
I have created folder structure as below.
export … from … is just a shorter notation for such import-export and both are behaving as similar.
export * from … re-exports only name exports, but ignores the default one.
The default export needs separate handle when re-exporting.