Search code examples
javascriptreactjsionic-frameworkionic5

How to trigger redirect with back direction in Ionic React 5?


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'}}
  />
);

Solution

  • 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.