reactjsreactstrap

Reactstrap modals


I want to take advantage of reactstarp modal. I also use it in the project eslintrc. I am showing such a mistake Line 17: Unused state field: 'modal' react/no-unused-state Line 26: Unused state field: 'modal' react/no-unused-state

this is my code

class AccountModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
    };

    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    const { state } = this.state;
    this.setState({
      modal: !state.modal,
    });
  }

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

    return (
      <div>
        <Button color="danger" onClick={this.toggle}>Delete account</Button>
        <Modal isOpen={state.modal} toggle={this.toggle}>
          <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
          <ModalBody>
            Deleting your account will remove all of
            your information from our database.
            This cannot be undone.
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={this.toggle}>Delete Account</Button>
            {' '}
            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

I do not know why the state is unused. I have copied the above code from the reactstarp documentation.


Solution

  • You are not accessing the state correctly. Try;

    toggle() {
        const { modal } = this.state;
        this.setState({
          modal: !modal,
        }); 
    }
    

    You should be able to access the modal property like in the render method as well.

    Explanation

    const { state } = this.state;
    

    this means that you are looking for an attribute with the name "state" inside "this.state",

    this.state = {
       modal: false,
    };
    

    whereas there is only one attribute named "modal" inside "this.state".