Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX working without importing React

Tags:

I'm trying to run my first React JSX file and it works! However, I don't have these two import statements included in my JSX:

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

I thought I would need these two imports so that when the JSX was transpiled to JS (by React.createElement), the React component would be in scope. But it seems to work even without the two imports.

How is it that this works without the imports?

Here is my code:

script.jsx:

var Main = React.createClass({
    getIntialState: function () {
        return {
            counter: 0
        };
    },
    clickHandler: function () {
        return {
            counter: this.state.counter + 1
        };
    },
    render: function () {
        return (
            <button onClick={this.clickHandler}>+2</button>
        )
    }
});

package.json

{
  "name": "reactjs",
  "version": "1.0.0",
  "description": "",
  "main": "react.js",
  "dependencies": {
    "webpack": "^1.13.3"
  },
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1"
  },
  "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "dev": "webpack --watch",
   "build": "webpack -p"
  },
  "author": "",
  "license": "ISC"
}

HTML file

<html>
<head>

    <title>
        !My first React JS Component!
    </title>
</head>
<body>
    <div id="root"></div>
    <script src="react.js"></script>
    <script src="output.js"></script>
</body>
</html>

webpack.config.js

module.exports = {
    entry: "./app/script.jsx",
    output: {
        filename: "output.js"
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader'
            }
        ]
    }
}
like image 219
JavaNovice Avatar asked Dec 03 '16 17:12

JavaNovice


1 Answers

It's because I have included react.js in my script tag as @DorWeid has pointed out. So it works even without the import. thanks all and sorry to be dumb!

like image 74
JavaNovice Avatar answered Sep 24 '22 17:09

JavaNovice