aboutjquery
aboutjquery

Reputation: 922

Reactjs eslint rule must use destructuring state assignment

class MyDrawer extends Component {
  const modalOpen = this.state;

  render() {
    return (
      <div>
        <Drawer
          modal
          open={this.state.modalOpen} // <-- this line show error [eslint] Must use destructuring state assignment (react/destructuring-assignment)
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }
}

export default MyDrawer;

I tried change the line to be const { modalOpen } = this.state; but now Failed to compile.

How can i follow the rule and edit my code to be Compiled successfully?

Upvotes: 5

Views: 11920

Answers (2)

Estus Flask
Estus Flask

Reputation: 222503

const is in wrong place. Only class members can be declared inside class MyDrawer extends Component {...}, and const is not allowed there. Destructuring assignment should reside inside a function where a variable should be available:

  render() {
    const { modalOpen } = this.state;

    return (
      <div>
        <Drawer
          modal
          open={modalOpen}
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }

Upvotes: 6

Tu Nguyen
Tu Nguyen

Reputation: 10179

Try this:

class MyDrawer extends Component {
  const { modalOpen } = this.state; //fixed

  render() {
    return (
      <div>
        <Drawer
          modal
          open={ modalOpen } // fixed
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }
}

export default MyDrawer;

Upvotes: 2

Related Questions