Reputation: 270
To import React we write import React from 'react'
.
But this is a default export right ? So if I change its name to something else other than React it should also work. But it doesn't work. Can anyone please explain why?
Upvotes: 7
Views: 398
Reputation: 628
Essentially, JSX compilers (like Babel/TypeScript) convert the JSX code to pure JavaScript.
For example, the following JSX code:
const Element = () => (
<div>
Hey there
</div>
);
is compiled into:
const Element = () => (
React.createElement("div", null, "Hey there")
);
Which is now valid JavaScript that can be parsed by the browser.
As you may have noticed, it uses the React.createElement
function to create the div
. This is why changing the name of the import doesn't work - the compiler still tries to use React
.
Babel lets you configure this using the pragma
option, if desired, allowing you to use a different function name.
TypeScript can do the same using the jsxFactory
compiler option.
Upvotes: 9
Reputation: 2272
It works so, as you use Babel, or something similar, to translate JSX. So when you input something like this:
function AComponent() {
return <div>Hello world</div>
}
You will get the next transpiled code:
"use strict";
function AComponent() {
return React.createElement("div", null, "Hello world");
}
By this reason you should use the definite name of React. You can try it here: https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=AQ4MwVwOwYwFwJYHsrAIIGEkFsAOKBTKOACgEpgBvAKFBACcC4J7UAeAEwQDcA-ACQIAbIUmAB3JPSEc2Aei59aoAL5A&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.4&externalPlugins=
Upvotes: 0