How to trigger a redirect to a given location with a given animation direction (say, back) in Ionic router without clicking a router link element?
There is a standard method to trigger a router redirect. The problem is that it can't change the animation direction so it's always forward:
// history is a value from react-router, it can be obtained from the HOC of the hook
history.push('/new/address');
There is also a method to go back, but it can't set a custom URL to go:
history.goBack();
I can also make a button and trigger a click on it, but it looks like an unwieldy solution:
const buttonRef = useRef();
const redirect = () => buttonRef.current.click();
return (
  <IonButton
    routerLink="/new/address"
    routerDirection="back"
    ref={buttonRef}
    style={{display: 'none'}}
  />
);
                There is an undocumented method to trigger an Ionic router redirect to any address with any animation: NavContext. It can be used only inside a React component.
import React, {Component, useCallback, useContext} from 'react';
import {NavContext} from '@ionic/react';
// Functional component example
function MyComponent() {
  const {navigate} = useContext(NavContext);
  // Call this function when required to redirect with the back animation
  const redirect = useCallback(
    () => navigate('/new/address', 'back'),
    [navigate]
  );
}
// Class component example
class MyComponent extends Component {
  static contextType = NavContext;
  // Call this method when required to redirect with the back animation
  redirect() {
    this.context.navigate('/new/address', 'back');
  }
}
The possible values for the second argument are the same as in the Ionic link components: back, forward and root.
As @Finesse points out, Ionic's react library provides the NavContext navigation context which exposes a couple of helpful methods in the, pun intended, context of navigation.
Among those is the goBack() method which simply navigates back. It takes a default route to navigate to. I guess that's for the case when there's no prior item on the back stack. It can be used as follows:
import {useContext} from 'react'
import {NavContext} from '@ionic/react'
...
const {goBack} = useContext(NavContext)
goBack('/alternative/path/if/empty/history')
...
Besides navigate() and goBack() the context provides these fields:
export interface NavContextState {
  getPageManager: () => any;
  getStackManager: () => any;
  goBack: (defaultHref?: string) => void;
  navigate: (path: string, direction?: RouterDirection | 'none', ionRouteAction?: 'push' | 'replace' | 'pop') => void;
  hasIonicRouter: () => boolean;
  registerIonPage: (page: HTMLElement) => void;
  currentPath: string | undefined;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With