Ionic Framework Tutorial: Build your first cross-platform app

ryanthelin

Ryan Thelin

Posted on December 4, 2020

Ionic Framework Tutorial: Build your first cross-platform app

The mobile app market is quickly becoming one of the best platforms to reach modern customers. A common problem faced by front-end developers is creating user interfaces (UI) that look and work well on all platforms: Android, iOS, or even as a web app.

Ionic UI software development kit is a common solution for this problem and allows front-end developers to make cross-platform apps with just a single codebase.

Today, we'll get you started with Ionic, show you how it fits with other web technologies, and help you create your first Ionic app.

Let's get started!

Here’s what we’ll cover today:

Master app UI development

Add Ionic to your skillset with hands-on practice with common front-end problems.

Developing Mobile Apps with Ionic and React

What is Ionic?

Alt Text

Ionic is an open-source software development kit (SDK) used to develop mobile, desktop, or Progressive Web Applications (PWA). It was originally built on top of AngularJS but now supports all the top front-end frameworks. You can use Ionic to build UIs for mobile apps created with Angular, React, or Vue.js.

Ionic even allows you to develop Ionic Native apps without any framework.

Ionic is used to create hybrid apps, which is essentially a web app that's been wrapped up in a native shell. The device installs the app container locally (like a native app), but the app uses an embedded browser to connect to any mobile platform capabilities. The embedded browser and any plugins are invisible to the user.

The biggest advantage of Ionic apps (and hybrid apps in general) is that you can build a single codebase then customize it for specific platforms like iOS, Android, or Windows.

The embedded browser separates the source code from the device and acts as a translator between the behavior outlined in the code and the specifics of the device. This platform-specific tuning allows you to create apps that perform and look great on any Ionic-supported platform.

The pros of using Ionic are:

  • Platform-specific tuning
  • Backend agnostic
  • Extensive built-in UI options and elements
  • Supported by top mobile and web platforms
  • Easy to pick up for those experienced in Sass, CSS, or HTML

The cons are:

  • Slow performance for Ionic Native apps (especially for graphics-heavy apps)
  • Plugin dependency, apps may fully break if a plugin is missing
  • No hot-reloading support, must restart the app to apply changes

How does Ionic work?

Ionic apps are built by combining built-in UI building blocks called Components. Ionic has thousands of UI Components in its library that are used to implement common forms like buttons, alerts, or input prompts. All built-in Components behave and look the same regardless of the platform.

Alt Text

Components allow you to build apps faster because you don't need to implement each common function from scratch. As a result, you can often complete all the barebones functionalities of your app in just a single sitting.

If you want to go beyond the standard library, you can also create custom Components. Custom Components can be reused across your application from then on.

Ionic Components are written in TSX, the TypeScript version of a JSX file. TSX is an extension of TypeScript that allows you to put HTML markup directly inside your code.

Here's an example of a TSX file that uses both TypeScript and HTML.

const fruit = [
  'Apples',
  'Oranges',
  'Grapes',
  'Peaches'];

return (
  <div>
    <h1>Hello, Ionic</h1>
    <p>Welcome to our app!</p>
    <h2>Here are some fruits</h2>
    <ul>
      {fruit.map((f) => <li>{f}</li>)}
    </ul>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Cordova

Ionic apps become hybrid apps with the inclusion of mobile app development framework Apache Cordova or Capacitor. These programs create the embedded browser layer that allows Ionic's web content to work in a native app. Once wrapped up with the embedded browser, your app functions as a native app and can be deployed to app stores on iOS, Android, Electron, or to the web as a PWA.

Without Cordova, web applications exist in a sandbox and cannot directly access a variety of hardware and software resources on the device. Cordova provides JavaScript API pathways to bridge the sandbox resource restrictions. Simply put, Cordova acts as a translator to allow your hybrid app to access the same resources as a native app.

Finally, Cordova can create virtual emulators of popular mobile platforms like Android or iOS to test your apps with.

Alt Text

Other frameworks

Ionic is often paired with other front-end frameworks like React and Angular.

Alt Text

React is a favorite front-end framework for mobile application development. Ionic supports a native React version with a setup identical to standard React apps.

Ionic React leverages DOM specific React functions with react-dom and implements React Router behind the scenes for routing and navigation. React Ionic is often used because of how closely it behaves and controls like standard React apps.

Alt Text

Angular is a front-end framework and is commonly used for enterprise apps. It is less beginner-friendly, but Ionic offers tools and APIs designed to help Angular developers seamlessly integrate the two technologies.

Ionic 4 and later use the official Angular stack for building and routing to ensure your Angular Ionic app fits perfectly with other Angular-focused tools.

Getting started with Ionic

Now that you've got some background knowledge, let's jump into the hands-on learning. First, we'll cover how to install Ionic, then move to the traditional Hello World program.

Installation

You'll need Node.js installed to install Ionic. We'll install the Cordova version of Ionic that includes both software.

Enter the following code into your command line.

sudo apt-get install nodejs
sudo apt-get install npm 
sudo npm install -g ionic cordova
Enter fullscreen mode Exit fullscreen mode

Wait for the command to run its course, and you'll have everything you need!

Hello World

Now we'll make a basic HelloWorld app to show you the ropes.

Step 1

First, create a folder, helloworld, for your project with the following command:

ionic start helloworld blank
Enter fullscreen mode Exit fullscreen mode
  • start signals to the CLI to create a new application.
  • helloworld will be the directory name and app name for your project.
  • blank selects the built-in blank template, which contains a single bare starter page.

When prompted, if you'd like to add Cordova plugins, type N or No.

Step 2

Change your directory to the helloworld directory we've just created. This will allow you to make changes to the project.

cd helloworld
Enter fullscreen mode Exit fullscreen mode

cd is short for "change directory".

Step 3

Open the helloworld folder in your files. You'll find a collection of pre-generated folders and blank file templates. Open src/page/home/home.html. We'll edit this file in the next step.

The other files in this section will be home.scss, which is the page to write your CSS code, and home.ts, where you can write TypeScript code.

Step 4

Delete any current text in the home.html file and replace it with the following:

 <ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Project
    </ion-title>
   </ion-navbar>
  </ion-header>

  <ion-content padding>
   <h2>Hello World </h2>
  </ion-content>
Enter fullscreen mode Exit fullscreen mode

The syntax for this section is nearly identical to HTML syntax. Our helloworld page is titled "Ionic Project" within the <ion-title> field. The only content in our app is the term "Hello World" within the h2 field.

Save the file changes and close home.html.

Step 5

Now, all we have to do is run your application with the following command:

ionic serve
Enter fullscreen mode Exit fullscreen mode

serve runs the application within the selected directory.

Once your app is running, type localhost:8100 into your URL bar to view the web app content.

Keep learning about Ionic

Speed up your app development and reach a larger user base by learning Ionic. Eduactive's hands-on courses help get you up to speed in half the time, without scrubbing through tutorial videos.

Developing Mobile Apps with Ionic and React

Make your first Ionic App

Now we'll generate a full application from the Ionicframework site and explore each piece.

First, go to the online Ionic app creator at ionicframework.com/start. Name your project firstapp, pick a theme color, and select the menu option. These options determine the start point of your Ionic project. Select React as your framework.

Next, you'll be asked to create an account or sign in. You'll then be given a custom-install command used to generate a program with the specifications provided.

Enter npm install followed by the custom-install command into your command line.

Then, enter cd firstapp to select the new project directory and enter ionic serve.

Your firstapp project will now be running.

If you don't want to generate the files on your end, you can use our examples files on our original blog post

Alt Text

Tour of Ionic React code

Let's take a deeper look at this app's code.

index.tsx

Open up the index.tsx file. This file is long, but the most important parts are at the top.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode
  • Line 1: At the top of the file, you can see an import statement for the react and react-dom libraries. Every app needs to import the React namespace to use React.
  • Line 2: The ReactDOM namespace provides methods specific to the HTML document object model that should be called from the top-most level of the application.
  • Line 3: The App import is pulling in the definition of the application itself.
  • Line 6: Calling ReactDOM.render() says to execute the App Component and place it inside the container specified by the second parameter. That container is an HTML element whose id attribute is root, which is in the index.html file found in the public folder.

index.html

This file contains many tags in <head> that control how the application renders on mobile devices. Ionic has already optimized this file so you should rarely have to alter it. Instead, make changes to the index.tsk file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Ionic App</title>

  <base href="/" />

  <meta name="color-scheme" content="light dark" />
  <meta name="viewport"
    content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="msapplication-tap-highlight" content="no" />

  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
  <link rel="shortcut icon" type="image/png" href="%PUBLIC_URL%/assets/icon/favicon.png" />

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-title" content="Ionic App" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
</head>

<body>
  <div id="root"></div>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

The body tag on line 25-27 contains a div paired to root to allow index.html to connect with index.tsx.

App.tsx

This file defines the App component. This is really where your application’s React code starts. App is defined as a constant arrow function, of the type React.FC. FC is short for FunctionComponent.

This function returns HTML to define the component. Most Ionic code appears in this HTML-like form.

const App: React.FC = () => {

  return (
    <IonApp>
      <IonReactRouter>
        <IonSplitPane contentId="main">
          <Menu />
          <IonRouterOutlet id="main">
            <Route path="/page/:name" component={Page} exact />
            <Redirect from="/" to="/page/Inbox" exact />
          </IonRouterOutlet>
        </IonSplitPane>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode
  • Line 3: The markup being returned. It is everything inside the return statement.
  • Line 4: The first thing in it is an IonApp. An IonApp is the root Ionic component that must appear on all Ionic-React pages.
  • Line 5: Inside of that is an IonReactRouter. This is Ionic’s thin wrapper around the React Router. The React Router is what lets you create multi-page applications with rich page transitions from a website with a single index.html file, also known as a Single Page Application (SPA).
  • Line 6: Inside of the IonReactRouter is an IonSplitPane component. This is the layout that provides the side-menu that collapses automatically to a hamburger menu on smaller screens.
  • Line 7: Inside of the IonSplitPane is a Menu component.
  • Line 8: As an immediate sibling to the Menu is an IonRouterOutlet. This is where your main page content appears. The Menu is on the left, and the IonRouterOutlet houses the rest of your application.
  • Line 9: Just inside of that are some defined routes. Think of a route as a URL. Given a path, /page/:name, the :name portion will be translated into a route variable called “name.”
  • Line 9: The component attribute has the component to load when the route matches. In this case, it is the Page component. The exact attribute means that this route will only match if the URL starts with a slash, followed by the word page, another slash, and then by one other word, which becomes the page “name.”

  • Line 10: The second route is a default route. It simply says that if the URL matched is a single slash character, redirect the application to /page/Inbox.

Page.tsx

Page is another component similar to App. The primary difference is that the FunctionComponent is a generic of type RouteComponentProps. This is what allows the Router to pass those route parameters.

In this case, it is expecting that route props to contain just a name, which it passes into the arrow function as the value match.

const Page: React.FC<RouteComponentProps<{ name: string; }>> = ({ match }) => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle>{match.params.name}</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">{match.params.name}</IonTitle>
          </IonToolbar>
        </IonHeader>
        <ExploreContainer name={match.params.name} />
      </IonContent>
    </IonPage>
  );
};
Enter fullscreen mode Exit fullscreen mode

Menu.tsx

Now open the menu.tsx file. This is where the side menu appearance and categories are defined.

Near the top of the file, it defines an AppPage interface, used to hold common properties about a page, such as its URL, icons, and title.

interface AppPage {
  url: string;
  iosIcon: string;
  mdIcon: string;
  title: string;
}
Enter fullscreen mode Exit fullscreen mode

Below is a selection of pages for each of our menu categories.

const appPages: AppPage[] = [
  {
    title: 'Inbox',
    url: '/page/Inbox',
    iosIcon: mailOutline,
    mdIcon: mailSharp
  },
  {
    title: 'Outbox',
    url: '/page/Outbox',
    iosIcon: paperPlaneOutline,
    mdIcon: paperPlaneSharp
  },
  {
    title: 'Favorites',
    url: '/page/Favorites',
    iosIcon: heartOutline,
    mdIcon: heartSharp
  },
  {
    title: 'Archived',
    url: '/page/Archived',
    iosIcon: archiveOutline,
    mdIcon: archiveSharp
  },
  {
    title: 'Trash',
    url: '/page/Trash',
    iosIcon: trashOutline,
    mdIcon: trashSharp
  },
  {
    title: 'Spam',
    url: '/page/Spam',
    iosIcon: warningOutline,
    mdIcon: warningSharp
  }
];
Enter fullscreen mode Exit fullscreen mode

Next, it defines the labels visible in the menu:

const labels = ['Family', 'Friends', 'Notes', 'Work', 'Travel', 'Reminders'];
Enter fullscreen mode Exit fullscreen mode

Below that is the React markup:

const Menu: React.FunctionComponent<MenuProps> = ({ selectedPage }) => {

  return (
    <IonMenu contentId="main" type="overlay">
      <IonContent>
        <IonList id="inbox-list">
          <IonListHeader>Inbox</IonListHeader>
          <IonNote>hi@ionicframework.com</IonNote>
          {appPages.map((appPage, index) => {
            return (
              <IonMenuToggle key={index} autoHide={false}>
                <IonItem className={selectedPage === appPage.title ? 'selected' : ''} routerLink={appPage.url} routerDirection="none" lines="none" detail={false}>
                  <IonIcon slot="start" icon={appPage.iosIcon} />
                  <IonLabel>{appPage.title}</IonLabel>
                </IonItem>
              </IonMenuToggle>
            );
          })}
        </IonList>

        <IonList id="labels-list">
          <IonListHeader>Labels</IonListHeader>
          {labels.map((label, index) => (
            <IonItem lines="none" key={index}>
              <IonIcon slot="start" icon={bookmarkOutline} />
              <IonLabel>{label}</IonLabel>
            </IonItem>
          ))}
        </IonList>
      </IonContent>
    </IonMenu>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • Line 6: The IonList component formats items into a list.
  • Line 8: The IonNote component provides headers.
  • Line 9: Here is some interesting code. The array map function is called on the appPages array to transform it into a series of IonMenuToggle components, which is used to toggle a menu open or closed.
  • Line 12: Inside of the IonMenuToggle is an IonItem, used to group other components, which in this case are an IonIcon and IonLabel, both of which should be self-explanatory. The IonItem has a routerLink attribute set to the value of the current page’s URL. This tells Ionic’s router to switch to that page.
  • Line 21: Below the menu is another list, generated the same way as the menu. The difference is it uses the label array and contains no routerLinks.

And there you have it! Now that you understand each of the parts of this beginner application, you can start adding your own personal touches.

What to learn next

Congratulations on completing your first Ionic App! The intuitive nature of this framework will allow you to quickly advance to advanced concepts and apps.

The next steps for mastering Ionic with React are to learn:

  • Different templates, tabs, lists, etc.

  • React Hooks with Ionic

  • Testing with Android and iOS emulators

To help you advance in half the time, Educative has created the Developing Mobile Apps with Ionic and React course. This course hands-on lessons on the creation, optimization, and deployment of cutting-edge Ionic apps. By the end, you'll have the expertise to manipulate all of the basic Ionic templates and have intimate knowledge on how to customize components to your needs.

Happy learning!

Continue reading about React and Web App Development

💖 💪 🙅 🚩
ryanthelin
Ryan Thelin

Posted on December 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related