kenshinji
kenshinji

Reputation: 2081

Why do I need import React statement even if I don't use React explicitly?

I have an React App, following is JavaScript code

import React from 'react';
import ReactDOM from 'react-dom';

const App = function(){
  return <div>Hi</div>
}

ReactDOM.render(<App />, document.querySelector('.container'));

And the HTML file is as following.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/style/style.css">
    <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAq06l5RUVfib62IYRQacLc-KAy0XIWAVs"></script>
  </head>
  <body>
    <div class="container"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

The question I don't understand is that if I remove import React from 'react', it will show error message like below.

Uncaught ReferenceError: React is not defined

But I don't use React in my code explicitly anywhere, why would it show a message like this. Can anyone tell me what's going on under the hood?

UPDATE: Not exactly the same question with this one, since what I have in my code is just an individual component, not involving any parent component.

Upvotes: 10

Views: 2202

Answers (1)

Gonzalo.-
Gonzalo.-

Reputation: 12672

Using JSX (<App />) is just a syntatic sugar for React.createElement().

So when your code is transpiled to pure javascript, references to React will appear there, so you need the import for that.

So yes, you're using it, although you don't see it

See what is your code transpiled to here

'use strict';

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var App = function App() {
  return React.createElement(
    'div',
    null,
    'Hi'
  );
};

_reactDom2.default.render(React.createElement(App, null), document.querySelector('.container'));

Upvotes: 21

Related Questions