Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If 'React' is the default export from 'react', Why can't we use some other name instead of 'React'

So, I was searching for some answer to this question and found that while importing, 'React' doesn't need to be in {} as it is the default export and not a named export, Well that's correct, but I have also seen that while importing a default export, we could use any name for it on import. But in this case, we can use only the below import,

import React from 'react';

and not

import Somename from 'react';
like image 810
Tinu Jos K Avatar asked Dec 13 '19 15:12

Tinu Jos K


People also ask

Why We Use Default export in React?

Export default means you want to export only one value the is present by default in your script so that others script can import that for use. This is very much necessary for code Reusability.

What is difference between export default and export in react JS?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.

How do you use named export in React?

Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.

Does not contain an export named Reactjs?

The "does not contain a default export" error occurs when we try to use a default import to import from a module that doesn't have a default export. To solve the error, make sure the module has a named export and wrap the import in curly braces, e.g. import {myFunction} from './myModule .


1 Answers

You can import React that way, but if you're using JSX, you also need to update your configuration to tell the transpiler that you're using that the "builder" function is no longer React.createElement, but is instead Somename.createElement. (If you're using Babel, you do that with the pragma directive.) That's because, as it says in the React documentation, this:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

Is transpiled to:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

...so React (or whatever name you change it to in the configuration) must be in scope. Other than that, it's fine.

like image 175
T.J. Crowder Avatar answered Oct 03 '22 12:10

T.J. Crowder