Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between import * as react from 'react' vs import react from 'react'

Tags:

reactjs

I am new to React or the coding background in general. And I am not sure what is the difference between the statements

import * as react from 'react' 

and

import react from 'react' 

Thanks in advance!

like image 204
Shravani Khatri Avatar asked Feb 08 '19 03:02

Shravani Khatri


People also ask

What is import * In React?

Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.

What is the use of import React from React?

Explanations: The JSX gets internally into many React. createElement() function calls and each of them returns an object as shown above. Now because of this, we need to import React from “react” since internally every JSX is creating a React Component using JSX transformer. then React.

What is import React component from React?

import React, { Component } lets you do class Menu extends Component instead of class Menu extends React. Component . It's less typing and duplication of the React namespace, which is generally a desired modern coding convention.

Do I need import React from React?

You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement . However, other exports like hooks must be imported.


2 Answers

There are 3 types of most import commonly used imports.

Type 1

import * as A from 'abc'; 

This will import everything which is marked as export in abc. You can access them using below code.

A.Component  

Type 2

import {A} from 'abc'; 

This will import A from abc, containing something like this:

export const A = () => {}; 

Type 3

import A from 'abc'; 

This will import the default export from abc as A. The export can look like this:

const B = () => {}; // The name "B" is not exported, only the value.  export default B;  // at the end of component 
like image 145
Anil Kumar Avatar answered Sep 24 '22 07:09

Anil Kumar


Pattern import * as React from 'react is related to the use of type systems in React like Flow or Typescript. Using import React from 'react' has led to issues with importing types definitions. For now in Typescript you can use allowSyntheticDefaultImports flag, which resolves this issue and imports all types even if you use import React from 'react'.

like image 35
Justine Avatar answered Sep 25 '22 07:09

Justine