Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to import React

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 ??

like image 463
Shivanand Mitakari Avatar asked Apr 12 '16 09:04

Shivanand Mitakari


People also ask

Should you always 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.

What is import in React JS?

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.

Why do we need to import React from React on the top of the file even if we don't use React?

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!

What is the purpose of using React?

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.


2 Answers

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').

like image 102
Ori Drori Avatar answered Oct 24 '22 09:10

Ori Drori


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

like image 42
Christophe Pouliot Avatar answered Oct 24 '22 09:10

Christophe Pouliot