0

I'm using the side menu template from Ionic React, so most of my logic is in ExploreContainer.tsx .

//imports

//some logic

const ExploreContainer: React.FC<ContainerProps> = ({ name }) => {
  switch( name ) {  //switch to show content on requested item from side menu
    case 'Home':
      return (
        //content for home
      );
    case 'Info':
      return (
        //content for info
      );
  }
};

export default ExploreContainer;

Now, since I'm building this for mobile, I'm using Capacitor. This enables me to listen for hardware back button events. When the user presses their back button, I want them to back taken back to 'Home' in this example. All answers I have found kind of always refer to buttons for navigation, where it's possible to declare a custom state and maybe use the <Redirect /> component.

Now, to extend the former example, lets say I want something like this:

//imports
import { Plugins } from '@capacitor/core';
    
const ExploreContainer: React.FC<ContainerProps> = ({ name }) => {

  Plugins.App.addListener("backButton", () => {
    name = "Home";
  }

  switch( name ) {  //switch to show content on requested item from side menu
    case 'Home':
      return (
        //content for home
      );
    case 'Info':
      return (
        //content for info
      );
  }
};

export default ExploreContainer;

Sadly, this does not work. Previously I've tried the following:

import { useHistory } from 'react-router-dom';

Plugins.App.addListener("backButton", () => {
  history.push("/page/Home");
});

This however leads to some really ugly behavior. The app completely reloads, all variables are reset, etc.

If I understand correctly, the name property of the ExploreContainer is a state that gets changed when the user selects an item from the menu, so normally the app doesn't need to reload.

How would I go about this?

traxx2012
  • 394
  • 2
  • 16

1 Answers1

-1
import { useHistory } from 'react-router-dom';

const history = useHistory();

Plugins.App.addListener("backButton", () => {
  history.push("/page/Home");
});
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
  • " This however leads to some really ugly behavior. The app completely reloads, all variables are reset, etc. " – traxx2012 Nov 20 '20 at 16:13