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 ??
If you use React, import React from 'react' is the first thing that you write in your code but if you have created a new react app using creat-react-app recently, you might have noticed that there is no import React statement at the top and your code works just fine.
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.
If you forget to import React, it will be undefined and the createElement call will fail. So make sure to always import React in your functional components too!
React allows developers to create large web applications that can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in the application.
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')
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With