How toggle multiple modals with one function and one state?

Viewed 883

I'm using mobx and I have multiple modals like "menuModal" , "feedbackModal", "reviewModal" and couple few more . For each modal I have a state "isMenuModalOpen", "isFeedbackModalOpen", "isReviewModalOpen". Depending on state modals open or close. And for each state I have a function that toggles state on click. Is that possible to use just one function and one state to handle all this modals.

@observable public isFeedbackModalOpen = false
@observable public isReviewModalOpen = false
@observable public isMenuModalOpen = false


@action.bound
public menuModalToggle() {
this.isMenuModalOpen = !this.isMenuModalOpen
}
@action.bound
public feedbackModalToggle() {
this.isFeedbackModalOpen = !this.isFeedbackModalOpen
}
@action.bound
public feedbackModalToggle() {
this.isReviewModalOpen = !this.isReviewModalOpen
}

onClick={() => {
        this.props.store.modal.feedbackModalToggle()
      }}
2 Answers

Yes, you could achieve it by setting your state variable depending on the name of the modal sent, like so :

switchModal = modal => ev => {
    this.setState(prevState => ({ [modal]: !prevState[modal] }))
}

And then bind your onClick function like the following. This will preset the function bound to the onClick with a given first value :

class ModalOpener extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            feedback: false,
            review: false,
            menu: false
        }
    }

    switchModal = modal => ev => {
        this.setState(prevState => ({ [modal]: !prevState[modal] }))
    }

    render() {
        return(
            <>
                <button onClick={this.switchModal('feedback')}>A</button>
                <button onClick={this.switchModal('review')}>B</button>
                <button onClick={this.switchModal('menu')}>C</button>
            </>
        )
    }
}

You can now access each values by doing this :

const { feedback, review, menu } = this.state

With useState hook:

const [openModal, setOpenModal] = useState({
  menu: false,
  feedback: false,
  review: false,
});

const toggleModal = modal => {
  setOpenModal({ ...openModal, [modal]: !openModal[modal] });
};

<button onClick={() => toggleModal("menu")}></button>;
Related