0

Do you have any idea this error? I am getting ESlint error for the following line visible={this.state.visible}

It says: "Must use destructuring state assignment"

It uses: "eslint-config-airbnb"

Thank you in advance

import React from 'react'
import { Button, Modal } from 'antd'

class EditProfile extends React.Component {
  state = { visible: false }

  showModal = () => {
    this.setState({
      visible: true,
    })
  }

  handleOk = e => {
    console.log(e)
    this.setState({
      visible: false,
    })
  }

  handleCancel = e => {
    console.log(e)
    this.setState({
      visible: false,
    })
  }

  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>
          Modal Card
        </Button>
        <Modal
          visible={this.state.visible}
          onCancel={this.handleCancel}
          footer={null}
          className="custom-modal-v1"
          centered
        >
          Text
        </Modal>
      </div>
    )
  }
}
export default EditProfile
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Volkan Haslak
  • 65
  • 1
  • 7
  • 1
    Probably expect you to do... `const { visible } = this.state;` in your render function. – dezfowler Jul 18 '19 at 19:13
  • This is a ESLint plugin rule: [`react/destructuring-assignment`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/destructuring-assignment.md) used by _eslint-config-airbnb_. – Emile Bergeron Jul 18 '19 at 19:15

2 Answers2

0

change your render function to this and then access visible directly. This is es6 destructing where you can extract key as a variable with same name. read more here

      render() {
          const { visible } = this.state; // destructing visible form state
          return (
              <div>
                  <Button type="primary" onClick={this.showModal}>
                      Modal Card
                  </Button>
                  <Modal
                      visible={visible}
                      onCancel={this.handleCancel}
                      footer={null}
                      className="custom-modal-v1"
                      centered
                  >
                      Text
                  </Modal>
              </div>
         )
     } 
-1

You just have to destructure the value from the state rather than using it like this.state.visible. Just use the state value like this

  render() {
   //Destructure value from state
   const { visible } = this.state

    return (
      <div>
        <Button type="primary" onClick={this.showModal}>
          Modal Card
        </Button>
        <Modal
          visible={visible}
          onCancel={this.handleCancel}
          footer={null}
          className="custom-modal-v1"
          centered
        >
          Text
        </Modal>
      </div>
    )
  }

Hope this helps !

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23