React import and export code from different Javascript files



Exports & Imports

In React projects, We split our code across multiple JavaScript files - so-called modules. You do this, to keep each file/ module focused and manageable.

To still access functionality in another file, you need to export  (to make it available) and import  (to get access) statements.

There are two different types of exports: default which is unnamed and named exports:

default

 export default ...; 

named

export const someData = ...; 

We can import default exports like this:

import someNameOfYourChoice from './path/to/file.js';

Named exports have to be imported by their name:

import { someData } from './path/to/file.js';

A file can only contain one default and an unlimited amount of named exports. You can also mix the one default with any amount of named exports in one and the same file.

When importing named exports, we can also import all named exports at once with the following syntax:

import * as nameOfYourChoice from './path/to/file.js';


Lets have some examples -

create item.js and write below code to it.

const item ={
name:"Bat"
}

export default item;

Here we have exported iteam as default. We can import as 

import item from './item';

___________________________________________________________________________________

For named exports lets create one utility.js

export const printLog = (data) => console.log(data);
export const PI = 3.14;

import as

import {printLog,PI} from './utility';

or 

import * as utility from './utility';

Comments

Popular posts from this blog

HashMap Implementation with a Balanced Tree

Most frequently asked interview questions and answers on Microservices Architecture

Core Java Interview Questions