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 ?
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! 馃憤
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: