Afsanefda
Afsanefda

Reputation: 3339

React How to destruct deep props in constructor?

I have the following constructor in my class component:

constructor(props) {
    super(props);
    this.state = {
      dirty: this.props.form.dirty // error happens here!
    };
  }

eslint returns an error for destructing the props. How is it possible for deeper props like this?

Upvotes: 0

Views: 366

Answers (2)

Piyush Rana
Piyush Rana

Reputation: 667

First of all, don't use this.props inside constructor as you are getting props as an argument. Secondly for destructuring, you could do something like this:

const {form: {dirty = 'any initial value in case of undefined'}} = props;
this.setState = {
   dirty
}

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

It is not a error per se. But you could use something like this to avoid the warning.

const { dirty } = props.form;
this.state = { dirty };

OR

const { form: { dirty } } = props;
this.state = { dirty };

Upvotes: 1

Related Questions