user9114864
user9114864

Reputation:

One function to close a specified modal?

I have a lot of modal in my jsx file, so, I thought I need to create a function with if condition to close a specified modal:

Like this:

toggleModal = () => {
    if(d){
        this.setState({
            modalIsOpen:{
                Modal1: !this.state.modalIsOpen.Modal1,
            }
        });
    }

    if(d){
        this.setState({
            modalIsOpen:{
                Modal2: !this.state.modalIsOpen.Modal2,
            }
        });
    }

    console.log('click modal');
};

Ok, now, I don't know what a condition to pass to if-condition to let it know which modal to open / close.

Upvotes: 1

Views: 42

Answers (2)

Brian Le
Brian Le

Reputation: 2686

Nice and neat, you just need to pass in the name of the modal:

const handleCloseModal = name => {
  this.setState(prevState => ({
    modalIsOpen: {
      ...prevState.modalIsOpen,
      [name]: !prevState.modalIsOpen[name]
    }
  }));
}

And call it like so:

this.handleCloseModal('Modal1')

Upvotes: 1

TypeIA
TypeIA

Reputation: 17250

Why not create a function that takes the name of the modal as an argument?

toggleModal = (modalName) => {
    const newState = {modalIsOpen: {}};
    newState.modalIsOpen[modalName] = !this.state.modalIsOpen[modalName];
    this.setState(newState);
    console.log('click modal');
};

...

toggleModal('Modal1');

Upvotes: 0

Related Questions