bp. bp. - 2 months ago 13
Node.js Question

What is the form of Javascript used in this class declaration?

This is from the table example from React-toolbox (which could use a tag)

class TableTest extends React.Component {
state = { selected: [], source: users };

handleSelect = (selected) => {
this.setState({selected});
};

render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source}
/>
);
}
}


This does not compile with webpack/babel for me but the following 'correct' Javascript does. Is this JSX notation and a sign that I'm not transpiling JSX as I think I am?

class TableTest extends React.Component {
constructor() {
super();
this.state = { selected: [], source: users };

this.handleSelect = (selected) => {
this.setState({selected});
};
}

render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source} />
);
}
}


Webpack/babel chokes on:

ERROR in ./src/client/app/app.jsx
Module build failed: SyntaxError: Unexpected token (21:8)

19 |
20 | class TableTest extends React.Component {
> 21 | state = { selected: [], source: users };

Answer

This is using class properties, which are currently part of Babel's stage 2 preset.

For this code, the = statements in the class body would get moved into the constructor by the class properties transform.

Here's the original code in the Babel REPL with suitable presets applied.

You will need to add this preset (or a lower stage preset, as all Babel stage presets also include higher stage features) to your Babel config, or add the transform plugin to it individually.

Example Babel config which would provide all the features you need to transpile the original code:

{
  presets: ['es2015', 'react', 'stage-2']
}