Reputation: 697
I know there are a lot of similar questions but I didn't found the solution and some of them are old so they don't apply.
I've created a Webpack environmental for react but doesn't compile JSX syntax.
I'm using:
"@babel/core": "^7.1.6",
"@babel/preset-env": "^7.1.6",
"@babel/preset-react": "^7.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
In my babel.config.js I have:
...
'presets': [
[
'@babel/preset-env',
{
'targets': {
'chrome': 61,
},
'modules': false,
'useBuiltIns': 'usage'
},
'@babel/preset-react'
]
],
...
I can compile react code like this:
import React from 'react'
import ReactDOM from 'react-dom'
require('./scss/main.scss')
const e = React.createElement
class LikeButton extends React.Component {
constructor (props) {
super(props)
this.state = {
liked: false
}
}
render () {
if (this.state.liked) {
return 'You liked this.'
}
return e(
'button',
{
onClick: () => this.setState({
liked: true
})
},
'Like'
)
}
}
const domContainer = document.querySelector('#like_button_container')
ReactDOM.render(e(LikeButton), domContainer)
but when I tried to use JSX
const name = 'Name';
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
it complain about the <
of the h1
Upvotes: 1
Views: 2282
Reputation: 799
const element
in your code is not a valid React component.
You need to return a function and always start component names with a capital letter.
// Always import React at the top of the file!
import React from 'react';
function Person(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Person name="Name of the person" />;
ReactDOM.render(
element,
document.getElementById('root')
);
More on components here: https://reactjs.org/docs/components-and-props.html
Upvotes: 0
Reputation: 1237
Move your @babel/preset-react
outside your config for @babel/preset-env
(move it outside the array), like this:
presets: [
["@babel/preset-env", {...}],
"@babel/preset-react",
]
@babel/preset-react
should be on the same level (top level for presets
) as your @babel/preset-env
.
Upvotes: 5