Reputation:
I am new to react am trying to write a simple click event functionality.
When I click choice the span tag with this class name
working small prototype code http://codepen.io/anon/pen/rxPvyr?editors=0110
actual code base trying to fix the error http://codepen.io/kk-/pen/BjeLry
Line 16: Direct super call is illegal in non-constructor, use super."constructor"() instead
14 |
15 | constructor(props) {
> 16 | super(props);
| ^
17 |
18 | this.handleClick = this.handleClick.bind(this);
Upvotes: 1
Views: 2576
Reputation: 8436
There are a couple idomatic ways to define a React class - it's possible you were mixing and matching styles, which of course is not supported:
ES5 - No constructor()
method, use getInitialState()
var React = require('react');
var SomeComponent = React.createClass({
getInitialState: function() {
return { message: 'hello world'};
},
render() {
return (
<div>{this.state.message}</div>
);
}
});
module.exports = SomeComponent;
ES6 - No getInitialState()
, use constructor()
Also, you must call super(props)
before invoking this
!
import React from 'react';
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state({
message: 'hello world'
})
}
render() {
return (
<div>{this.state.message}</div>
);
}
}
SomeComponent.propTypes = {};
export default SomeComponent;
UPDATE: If one forgets to call super(props)
in constructor()
, but then attempts to access this
, the following error will be thrown: 'this' is not allowed before super()
:
Module build failed: SyntaxError: C:/_workspaces/hello-world/some-component.jsx: 'this' is not allowed before super()
20 | class SomeComponent extends React.Component {
21 | constructor(props) {
> 22 | this.state = {
| ^
23 | message: 'hello world'
24 | }
25 | }
Here's a little more info on why it's required: https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors-when-declaring-components-using-es6-classes/2781
ES6 Static No internal methods, just an implied render()
import React from 'react';
const SomeComponent = ({
message
}) => (
<div>{message}</div>
);
SomeComponent.propTypes = {};
export default SomeComponent;
Upvotes: 6