I created a jsx file as below
/** @jsx dom */
(function(){
'use strict';
define([
'jquery',
'react',
'react-dom'
],
function($, React, ReactDOM){
var AppView = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<AppView />, document.getElementById('dsl-application'));
});
})();
And transformed the jsx to js using below command
babel --watch src --out-dir bundle --preset react
And the out put file is like below
(function () {
'use strict';
define(['jquery', 'react', 'react-dom'], function ($, React, ReactDOM) {
var AppView = React.createClass({
displayName: 'AppView',
render: function () {
return dom(
'div',
null,
'Hello World'
);
}
});
ReactDOM.render(dom(AppView, null), document.getElementById('dsl-application'));
});
})();
The problem is I got Uncaught ReferenceError: dom is not defined when I run the js file in browser. dom is added after transformation. Any clue how to fix this?
What is the DOM? The DOM (Document Object Model) represents the web page as a tree structure. Any piece of HTML that we write is added as a node, to this tree. With JavaScript, we can access any of these nodes (HTML elements) and update their styles, attributes, and so on.
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.
Run into this same issue with a basic React app.
Turned out that the culprit was in my webpack.config.js. I had:
plugins: [
["transform-react-jsx", {
"pragma": "dom"
}]
]
babel's default pragma is React.createElement (https://babeljs.io/docs/plugins/transform-react-jsx/).
The truth is that I had no reason for this option, I had just copy/pasted from the link above.
From the docs, I should have imported the 'dom' module that I had specified and made sure I had babel-plugin-jsx-pragmatic installed.
The docs for this plugin are here https://www.npmjs.com/package/babel-plugin-jsx-pragmatic and explain a little bit about pragmas.
I fixed this issue by simply removing the 'pragma' option so I could just use the default one ( attached a part of my webpack.config.js to provide more context): -- I am using webpack 2.6.1
...
module: {
rules: [{
//a regexp that tells webpack to use the following loaders on all
//.js and .jsx files
test: /\.js$/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: ["es2016", "react", "stage-0"],
plugins: [
["transform-react-jsx"]
]
},
//we definitely don't want babel to transpile all the files in
//node_modules. That would take a long time.
exclude: /node_modules/
},
...
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