0

Regarding a lint code validation error:

error  Must use destructuring props assignment  react/destructuring-assignment

I am new to the concept of destructuring properties and I am a bit confused about how I am supposed to use a destructing approach to the following code:

  constructor(props) {
    super(props);
    this.state = {
      clickedFirstTime: !this.props.showDefault,
    };
  }

Note to other people finding this on Google, I have read the following resources to help me understand what destructuring was, but I am just unable to figure out how to do it in this case:

FMaz008
  • 11,161
  • 19
  • 68
  • 100
  • 2
    You should *not* use destructuring here. Disable the rule, it just has too many false positives. – Bergi Dec 12 '20 at 17:49
  • I feel like I should have a better follow up question but all I can think of is: really? Why was that rule added if it is so bad ? – FMaz008 Dec 12 '20 at 19:18
  • 1
    Link to how to do this: https://stackoverflow.com/questions/51222448/prop-destructuring-inside-of-react-state , answer by Almaju – FMaz008 Dec 12 '20 at 19:25

2 Answers2

2

The rule wants you to never write this.props.…. In this case, it's looking for

constructor(props) {
  super(props);
  const { showDefault } = this.props;
  this.state = {
    clickedFirstTime: !showDefault,
  };
}

But really your code is fine, and you should just disable the rule if it is annoying.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I'm not very strong on my feet yet, so I'd rather keep an annoying rule until I really know I am being annoyed and not wrong or lazy. Dealing with this made me understand destructuring and props spreading. So I guess it was a good thing the rule was there ;) – FMaz008 Dec 12 '20 at 20:03
0
  constructor({...props}) {
    super(props);
    this.state = {
      clickedFirstTime: !this.props.showDefault,
    };
  }