Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 302
aboutjquery Avatar asked Sep 29 '18 04:09

aboutjquery


2 Answers

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>
    );
  }
like image 80
Estus Flask Avatar answered Nov 03 '22 07:11

Estus Flask


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;
like image 25
You Nguyen Avatar answered Nov 03 '22 08:11

You Nguyen