Import and Export in REACT

Import and Export in REACT

ยท

2 min read

In my early days of writing software (React), I had issues understanding import and export, regardless of the fact I was always using them.

I hope with my article anyone confused will learn and no longer have challenges using import and export.

Export & Import:

There are 2 types of Export, export default and normal export they are a little bit similar but have a few differences.

So let's talk about normal export and how they are imported.

export interface ITask{
taskName: string;
deadline: number;
}

So I am basically exporting that interface to be used in another file.

Here is how we import it, we use the exact name we named it in the export and destructure it.

Let's go.

import {ITask} from "./interfaces"

When ever we use export default there are basically 2 ways they can be imported either by destructuring each elements (functions) in the file and importing it directly or by naming the export and importing it with the name or by renaming it.

So assuming we have a file called auth and in our auth.js file we have functions like logout(), login() and then wrap it in an object.

export default {login,logout};

And then import by

import {login, logout} from "auth"

Or we import it in a named pattern without destructuring.

import auth from "auth"
//We can now use our functions in the auth like 

auth.login();
auth.logout();

In React we export components as named exports and also import as a named import

export default TodoTask;

And then import as

import TodoTask from "../TodoTask"

Assuming we have functions like axios.get & axios.post

And rename the export to be

export default {
get: axios.get,
post: axios.post,
}

So we can either import th whole object in a named way or in an unnamed way

import {get,post} from "http";
//OR
import http from "http";

//we can now do 
http.get()
http.post()

It's that clean and simple ๐Ÿ˜Œ

Thank you for reading ๐Ÿ“š Happy coding โค

ย