4

I've seen a lot of threads about calling multiple traditionally declared functions in React onclick, but I'm confused how I could implement that with arrow functions. I have a function called handleClose, which closes a Material UI menu:

const [open, setOpen] = React.useState(false);
const anchorRef = React.useRef(null);
const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }
    setOpen(false);
  };

And I have a function called handleModalOpen, which open a Material UI Modal:

const [modalOpen, setModalOpen] = React.useState(false);
const handleModalOpen = () => {
  setModalOpen(true);
};

When I click this menu item, I would like both functions to run. Both functions individually work fine on their own. So how would I achieve this? (Currently I only have it set so the modal opens)

<MenuItem onClick={handleModalOpen}>Add Album</MenuItem>

Basically I have a button that triggers a menu, and then clicking one of those menu options should trigger a modal whilst closing the menu. Also, this is a functional component.

Evan Hsueh
  • 139
  • 1
  • 2
  • 9
  • 2
    Does this answer your question? [Call multiple functions onClick ReactJS](https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs) – Emile Bergeron Jun 28 '20 at 19:46

1 Answers1

6

Either you can create an inline arrow function which calls the both

<MenuItem onClick={(e) => {handleModalOpen(); handleClose(e); }}>Add Album</MenuItem>

Or you can create a function outside and pass its reference

handleClick = (e) => {
  handleModalOpen(); 
  handleClose(e);
}

<MenuItem onClick={handleClick}>Add Album</MenuItem>
Siddharth
  • 1,200
  • 8
  • 13