Skip to content Skip to sidebar Skip to footer

Direct Super Call Is Illegal In Non-constructor, Use Super."constructor"() Instead

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 I wrote a small prototype in codepen and its workin

Solution 1:

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()

varReact = require('react');

varSomeComponent = 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!

importReactfrom'react';

classSomeComponentextendsReact.Component {
    constructor(props) {
        super(props);
        this.state({
            message: 'hello world'
        })
    }
    render() {
        return (
            <div>{this.state.message}</div>
        );
    }
}

SomeComponent.propTypes = {};

exportdefaultSomeComponent;

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 | classSomeComponentextendsReact.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()

importReactfrom'react';

constSomeComponent = ({
    message
}) => (
    <div>{message}</div>
);

SomeComponent.propTypes = {};

exportdefaultSomeComponent;

Post a Comment for "Direct Super Call Is Illegal In Non-constructor, Use Super."constructor"() Instead"