Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prop destructuring inside of react state

I've added airbnb config for eslint that encourages prop and state destructuring, I like it, but stumbled across one problem when I define state in my component

class MyComponent extends Component {
  state = {
    animation: this.props.active ? 1 : 0
  }

I get an error

[eslint] Must use destructuring props assignment (react/destructuring-assignment)

I'm not sure how can I correctly destructure active out of props here? Usually const {active} = this.props works, but whenever I place it inside state or around it I get unexpected syntax error.

like image 607
Ilja Avatar asked Jul 07 '18 10:07

Ilja


People also ask

Can I Destructure props in React?

Destructuring is a simple property that is used to make code much clear and readable, mainly when we pass props in React.

Can you Destructure state in React?

Destructuring stateDestructuring states is similar to props. Here is syntax to Destructuring states in React: import React, { Component } from 'react' class StateDemp extends Component { render() { const {state1, state2, state3} = this.

What is Destructuring in React example?

Destructuring is a convenient way of creating new variables by extracting some values from data stored in objects or arrays. To name a few use cases, destructuring can be used to destructure function parameters or this. props in React projects for instance.


2 Answers

You can add this rule to .eslintrc.json

"rules": {
    "react/destructuring-assignment": [
      "error",
      "always",
      {
        "ignoreClassFields": true
      }
    ]
  },
like image 145
Almaju Avatar answered Oct 09 '22 13:10

Almaju


The only to keep it inside of the class property is to use a getter (which will be invoked at the first render):

state = {
  get animation() {
    const { active } = this.props;
    return active ? 1 : 0;
  }
}

Or you use an IIFE to initialize the property:

state = (() => {
  const { active } = this.props;
  return { animation: active ? 1 : 0 };

})()

But thats actually a bit overcomplicating. Another solution would be to move the property into the constructor:

constructor(...args) {
 super(...args);

 const { active } = this.props;
 this.state = { animation: active ? 1 : 0 };

}

But I personally would just ignore that warning here.

like image 37
Jonas Wilms Avatar answered Oct 09 '22 11:10

Jonas Wilms