Eslint-plugin-react: Must use destructuring state assignment error for accessing variable state keys

Created on 9 Sep 2019  路  5Comments  路  Source: yannickcr/eslint-plugin-react

I am trying to access variable key from my react state.
like: if (typeof this.state[field] === 'object'))

while doing so I am getting the error Must use destructuring state assignmenteslint(react/destructuring-assignment)
In this case i wont be able to de structure the state. Is this something frowned upon ?

question

Most helpful comment

Initial state with props is incorrect unless it鈥檚 also using getDerivedStateFromProps.

Functions should not go in class fields, so you want this:


class EmailInput extends Component {
  state = {};

  static getDerivedStateFromProps({ defaultEmail }) {
    return { email: defaultEmail };
  }

  handleChange = this.handleChange.bind(this);
  handleChange(event) {
    this.setState({ email: event.target.value });
  }

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}

All 5 comments

const { [field]: something } = this.props;

Didn't knew we de-structure variable field like this as well.
Thanks @ljharb for the help.

@ljharb
Hi~ If I would like to write a component that just what this blog saying.
The draft input component has initial state with props, and the state using class fields syntax. How to destruct it?

class EmailInput extends Component {
  state = { email: this.props.defaultEmail };

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}

Initial state with props is incorrect unless it鈥檚 also using getDerivedStateFromProps.

Functions should not go in class fields, so you want this:


class EmailInput extends Component {
  state = {};

  static getDerivedStateFromProps({ defaultEmail }) {
    return { email: defaultEmail };
  }

  handleChange = this.handleChange.bind(this);
  handleChange(event) {
    this.setState({ email: event.target.value });
  }

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}

Wow, that's cool. Thanks for help! 馃憤

Was this page helpful?
0 / 5 - 0 ratings