Reputation: 515
I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead
import ReactDOM from 'react-dom'
import React, {Component} from 'react'
class App extends Component {
render () {
return (
<div>comp </div>
)
}
}
//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(<div>sv</div>, document.getElementById('root'))
why its require to import React ??
Upvotes: 17
Views: 3047
Reputation: 2517
For React versions prior to React 17 or the specified older major versions not including the new JSX transform (see blog), importing React in every component file is necessary for the JSX transform. However in React 17 and some specified older versions including the new transform, this is no longer necessary because of its new transform that does not require it.
Reference: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
Upvotes: 2
Reputation: 331
You need to import React if using the JSX DSL (which almost everybody does)
As per other answers, a transpiler will usually change JSX tags to
React.createElement(...)
So you actually are using React :)
Upvotes: 0
Reputation: 176
This is a really interesting question, since you're right that the code doesn't look like it's using React, but it's being tricky.
Any time you use the shorthand <Component />
code what's actually happening is the JSX is transpiled by Babel into something that is regular Javascript.
<Component/>
// Is turned into
React.createElement(...)
Therefore the code does indeed need React to be imported, although it's not obvious to the reader
Upvotes: 4
Reputation: 1602
React import is required because the following JSX code:-
(
<div>comp </div>
)
gets transpiled to
React.createElement(
"div",
null,
"comp "
);
This is the reason you need to import React; I hope that answers your question.
You can always refer to https://babeljs.io to understand what get's converted to what.
Upvotes: 3
Reputation: 191946
Although you don't explicitly use the React instance you've imported, JSX is transpiled to React.createElement()
call, which uses it.
In your example, <div>comp </div>
is transpiled by Babel to React.createElement('div', null, 'comp')
.
Upvotes: 21
Reputation: 457
I used to think that if ReactDOM uses React then it will take care of importing it. But that's not the case. After JSX in your source code is transformed it is evident that its explicitly using the React package. And hence it is required.
React.createElement('div', null, 'comp')
Upvotes: 0