New YouTube video!How to use the Capacitor Google Maps plugin with Ionic React

Watch now →
Opens in a new tab

Blog

Blog posts and tutorials about Ionic, Capacitor, Javascript, React and Mobile App Development

← Back

Routing, programmatically in Ionic React

avatar for Routing, programmatically in Ionic React

By Alan Montgomery
Let's connect!
 on 3rd June 2021 in Routing3 min read

Ionic React Hub Blog - Routing, programmatically in Ionic React

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;

  1. goBack() This method will navigate backwards in history, using the IonRouter to determine history. It accepts one argument for an optional custom transition if wanted

    • animationBuilder?: AnimationBuilder- Optional - A custom transition animation to use
  2. 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.
    • 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.
  3. 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.

  4. 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 👋

Discuss

Share this post

Level up your Ionic React skills. I'll send you handpicked tutorials, examples & resources

Plus, you'll be the first to know about premium content!

ionic logo

Read More...

A really easy to use solution for building forms and validation in your Ionic React mobile apps.

Forms

Using React Hook Form to build forms and validation in Ionic React

A really easy to use solution for building forms and validation in your Ionic React mobile apps.

7th July 2021

5 min read

Simple and effective way to create an add to cart animated button in Ionic React with Ionic Animations.

Animations

Using Ionic Animations to create an add to cart animated button in Ionic React

Simple and effective way to create an add to cart animated button in Ionic React with Ionic Animations.

11th June 2021

5 min read

I want to show you what tech and plugins I used to build this website and blog.

General

How I built this website and blog

I want to show you what tech and plugins I used to build this website and blog.

2nd June 2021

4 min read