Import and Export in React

Rajitha Sanjayamal
3 min readNov 7, 2022

--

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.

file — Messages.jsx

Also we can place export separately.

file — Messages.jsx

Import

We put a list of what to import in curly braces. import {….} , like that.

file — App.js

If there are many things to import, we can import everything as an object using import * as .

file — App.js

Import “as”

We can use as to import under different names. Let’s import HelloComponent with name Hello and ByeComponent as Bye.

file — App.js

Export ‘’as’’

This syntax is similar as previous. We can export with different names using as.

file — Messages.jsx
file — App.js

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.

file — Messages.jsx

Import without curly braces.

file — App.js

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.

file — Messages/index.js

export … from … is just a shorter notation for such import-export and both are behaving as similar.

file — Messages/index.js

export * from … re-exports only name exports, but ignores the default one.

file — Messages/index.js

The default export needs separate handle when re-exporting.

file — Messages/index.js

--

--

Rajitha Sanjayamal
Rajitha Sanjayamal

Responses (2)