How can I programmatically close the side menu in Ionic React?

I have a side menu that successfully routes between pages. However, after routing the menu does not close automatically. I am assuming I can do this programmatically, but cannot figure out how to invoke the close() method on the IonMenu React component. Any ideas?

<IonMenu ref={menuRef} side='start' type='overlay' contentId='main-content'>
   <IonItem button routerLink={page.path}>
      <IonLabel>Home</IonLabel>
   </IonItem>
</IonMenu>
import { menuController } from "@ionic/core";
<IonButton onClick={async () => await menuController.toggle()}>
   Toggle Menu
</IonButton>
5 Likes

This doesn’t appear to work with @ionic/react@5.0.5… Neither menuController.toggle() nor menuController.close() close the (unique) menu.

@JonathanMinson, have you succeeded to close the menu ?

@JonathanMinson, I figured it out. The Ionic React Conference App uses some IonMenuToggles around the IonItems of the menu.

See : https://github.com/ionic-team/ionic-react-conference-app/blob/0f5774d5adb7b25fe3b9c4bc2ccde5e7d250138d/src/components/Menu.tsx#L64

I just tested this code and it does actually work… Can you be more specific in the use case where it doesn’t work?

Aaron’s solution worked for me. I’ve adapted to my use case:

const navigateToPage = (page: Page) => {
        setActivePage(page.title);
        setTimeout(() => menuController.toggle(), 250);
    };

I would just add to @aaronksaunders soultion, if you have more then one menu, you can specify which one with menuController.toggle(“specific_menu_id”).

If the above didn’t work for you, check this out.

1 Like

Late to the party, but seems one can invoke the menu method(s) on the ref instance:

const menuRef = React.useRef<HTMLIonMenuElement>(null);

<IonMenu ref={menuRef} contentId="main-content">
  ...
</IonMenu>

then call it wherever: menuRef.current?.close() or menuRef.current?.toggle()

3 Likes

This was actually really helpful, thank you

Great help - thank you