简体   繁体   中英

problems with babel react preset and react-dom

I'm using webpack and babel to pre-process my jsx files to javascript. My configuration looks like this:

Webpack.config.js

module.exports = {
    entry: "./react/main.jsx",
    output: {
        path: __dirname,
        filename: "./public/javascripts/app.js"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    }
};

./react.main.jsx

import { render } from 'react-dom'
import HelloWorld from './components/helloworld.jsx'
render(<HelloWorld />,document.body);

./react/components/helloworld.jsx

import React from 'react'

class HelloWorld extends React.Component {
    static render() {
        return (
            <div>
                <h1>Hello World!</h1>
                <p>This is some text</p>
            </div>
        );
    }
}

export default HelloWorld;

When I run webpack I keep getting the error React is not defined at this line in app.js

(0, _reactDom.render)(React.createElement(_helloworld2.default, null), document.body);

If I specifically include react in my main.jsx file that error goes away and then the error is

Uncaught Invariant Violation: _registerComponent(...): Target container is not a DOM element. pointing to the null value as the second parameter of React.create element in app.js

I'm sure it's something I'm missing or doing wrong, but I don't know what it is.

Add this line of code into your main.jsx file.

import React from 'react'

as a react-dom uses react , but the primary reason is that the file contains JSX and JSX is just converted to React.createElement calls - Felix Kling

From upgrade Guide React v0.14

Passing document.body directly as the container to ReactDOM.render now gives a warning as doing so can cause problems with browser extensions that modify the DOM.

So change your markup to

<body>
  <div id="app"></div>
</body>

After that you can render your component to the div tag

render(<HelloWorld />,document.getElementById('app'));

Thanks

Thanks for the help everyone. I didn't realize that react-dom didn't require 'react' on its own. at any rate, the other half of the issue was the placement of app.js after it was compiled. I put it at the bottom after the body and everything worked perfectly. I did get a warning about document.body so I'll change that to use a div instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM