Search code examples
reactjsinheritanceconstructorsetstate

How do I initialize state when I'm extending a component?


I have a component called ErrorComponent whose state is initialized in its constructor.

However, I now want to make a new class called BaseForm that extends from ErrorComponent.

But if I do

export default class BaseForm extends ErrorComponent {
    constructor(props) {
            super(props);
            this.setState({
                reason: null
            });

it yells at me and says I shouldn't use setState in the constructor.

And if I do

export default class BaseForm extends ErrorComponent {
    constructor(props) {
            super(props);
            this.state = {
                reason: null
            };

It seems to be overwriting the state from the ErrorComponent constructor. How do I set the state without overriding the state from the class I'm extending from?


Solution

  • export default class BaseForm extends ErrorComponent {
        constructor(props) {
                super(props);
                this.state = Object.assign(this.state, {
                    reason: null,
                });