Reputation: 498
Learning React, and I'm looking over Google's MaterialUI docs, and it shows a syntax that looks like:
export default class DialogExampleModal extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
...
Babel with es2015 is failing on the state= part of this code:
ERROR in ./client/App.jsx
Module build failed: SyntaxError: Unexpected token (23:8)
21 | }
22 |
> 23 | state = {
| ^
24 | open: false,
25 | };
26 |
My question is, what is this syntax and do I have something possibly configured wrong? It seems that other ES2015 syntax works fine.
Upvotes: -1
Views: 117
Reputation: 6564
I think you either need to set class' properties inside the constructor like this:
export default class DialogExampleModal extends React.Component {
constructor() {
this.state = {
open: false,
};
this.handleOpen = () => {
this.setState({open: true});
};
}
}
or you can use transform-class-properties
babel plugin, to make code from your question compile.
Upvotes: 2
Reputation: 1392
Well, the first thing that jumps out to me is that the sample code has an open brace before the state code and yours has a closing bracket.
export default class DialogExampleModal extends React.Component { // HERE
state = { // HERE
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
And yours:
21 | } // HERE
22 |
> 23 | state = {
If you are closing the component before the state function, it will throw an error because it is an undefined function it isn't expecting outside the component.
If that is another function inside the component, you need a semicolon after it.
21 | }; // SEMICOLON HERE
22 |
> 23 | state = {
Upvotes: 0