Today I want to teach you how you can achieve routing programmatically in Ionic with React. There are a few different ways it can be done, but there's one way that should definitely be utilised, especially in the day and era we live in with hooks
and the functionality we're provided with out-of-the-box by Ionic!
I've found it hard in the past, along my journey to come across docs and resources in one place detailing these miniscule, specific use cases, and I want to start creating valuable, short pieces of information to help you on your Ionic React journey too, all in one place!
💥 Let's get started.
useIonRouter hook
This is a React hook
that comes baked into the Ionic Framework by default. It gives us as developers more direct control over routing in an Ionic React applicaiton.
All we need to do is import it;
import { useIonRouter } from "@ionic/react";
Now, because this is a hook, we need to obey by the rule of hooks in React. What's that?
You must only call hooks inside inside a function. Never inside a loop, or other conditional statement etc and always at the top level.
Just think of it like your standard local useState
hook call within a component that you're probably already familiar with.
Initializing the hook
Lets say we have a component called Page1.js
and at the top of this functional component we can initialize our hook like so;
import { useIonRouter } from "@ionic/react";
export const Page1 = () => {
const router = useIonRouter();
}
Methods and usage of the useIonRouter hook
We have access to a few very useful built-in methods we can use to navigate through our app, these are;
-
goBack()
This method will navigate backwards in history, using the IonRouter to determine history. It accepts one argument for an optional custom transition if wantedanimationBuilder?: AnimationBuilder
- Optional - A custom transition animation to use
-
push()
This method allows us to push a route into the history of the router. This also accepts a few additional arguments to pass to the method. These are;-
pathname: string
- The path to navigate to - e.g.
/page2
.
- The path to navigate to - e.g.
-
routerDirection?: RouterDirection
- Optional - The RouterDirection to use for transition purposes, defaults to 'forward', can also be 'back', 'none' and 'root'.
-
routeAction?: RouteAction
- Optional - The RouteAction to use for history purposes, defaults to 'push', but can also be 'pop' and 'replace'.
-
routerOptions?: RouterOptions
- Optional - Any additional parameters to pass to the route.
-
animationBuilder?: AnimationBuilder
- Optional - A custom transition animation to use.
-
-
canGoBack()
Determines if there are any additional routes in the the Router's history. However, routing is not prevented if the browser's history has more entries. Returns true if more entries exist, false if not. -
routeInfo
This will show some information about the current route.
Now let's see how we can implement this in a real piece of code, following on from earlier in the post;
NOTE
Let's assume that all routes and pages/tabs and main
IonApp
is already set up and working. This is simply a demonstration of how to use the router from within a component/page.
import { useIonRouter } from "@ionic/react";
export const Page1 = () => {
// Initializing our router
const router = useIonRouter();
// A simple, hard-coded navigation
const simpleNavigate = () => {
router.push("/page2", "forward", "push");
}
// A more usable, dynamic navigate function
// Passing in the path and direction
// Working out the action based on direction
const dynamicNavigate = (path, direction) => {
const action = direction === "forward" ? "push" : "pop";
router.push(path, direction, action);
}
// Checking if we can go back
// Before calling the goBack() method
const navigateBack = () => {
if (router.canGoBack()) {
router.goBack();
}
// else...
}
return (
<IonPage>
<IonContent>
// Calling a function which calls the push method
<IonButton color="primary" onClick={ simpleNavigate }>
Go to Page 2
</IonButton>
// Calling a function which calls the push method
// But is dynamic, and we have control
<IonButton color="primary" onClick={ () => dynamicNavigate("/page3", "forward") }>
Go to X
</IonButton>
// Calling a method of the router directly
<IonButton color="secondary" onClick={ () => router.goBack() }>
Go Back
</IonButton>
</IonContent>
</IonPage>
);
}
Awesome, right? That's pretty much it! You can see how easy Ionic have made it for us with this useIonRouter
hook, however sometimes having a little context is good!
I really hope you enjoyed this little tutorial on routing programmatically in Ionic React! Be sure to sign up below to receive emails about new posts like these directly and all future content!
Let me know what you think via Twitter, you can share using the Twitter button below!
See you in the next one 👋