Categories
React Ionic

Mobile Development with Ionic and React — Alerts, Badges, and Buttons

If we know how to create React web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with React.

Alerts

We can add alerts to our Ionic React app by writing:

import React, { useState } from 'react';
import { IonAlert, IonButton, IonContent } from '@ionic/react';
import './Tab1.css';

const Tab1: React.FC = () => {
  const [showAlert, setShowAlert] = useState(false);

  return (
    <IonContent>
      <IonButton onClick={() => setShowAlert(true)} expand="block">Show Alert</IonButton>
      <IonAlert
        isOpen={showAlert}
        onDidDismiss={() => setShowAlert(false)}
        cssClass='my-custom-class'
        header={'Alert'}
        subHeader={'Subtitle'}
        message={'This is an alert message.'}
        buttons={['OK']}
      />
    </IonContent>
  );
};

export default Tab1;

We add the useState hook to control the showAlert state.

Then we can sue that to control the opening of the alert with the IonButton component.

The isOpen prop controls whether the alert is open or not.

onDidDismiss lets us run something when we dismiss the alert.

cssClass has the CSS class for the alert.

header has the alert header.

subHeader has the alert subheader.

message has an alert message.

buttons have the buttons for the alert.

We can event handlers to the buttons and customize them.

For example, we can write:

import React, { useState } from 'react';
import { IonAlert, IonButton, IonContent } from '[@ionic/react](https://medium.com/r/?url=http%3A%2F%2Ftwitter.com%2Fionic%2Freact "Twitter profile for @ionic/react")';
import './Tab1.css';

const Tab1: React.FC = () => {
  const [showAlert, setShowAlert] = useState(false);

return (
    <IonContent>
      <IonButton onClick={() => setShowAlert(true)} expand="block">Show Alert</IonButton>
      <IonAlert
        isOpen={showAlert}
        onDidDismiss={() => setShowAlert(false)}
        cssClass='my-custom-class'
        header={'Alert'}
        subHeader={'Subtitle'}
        message={'This is an alert message.'}
        buttons={[
          {
            text: 'Cancel',
            role: 'cancel',
            cssClass: 'secondary',
            handler: blah => {
              console.log('Confirm Cancel: blah');
            }
          },
          {
            text: 'Okay',
            handler: () => {
              console.log('Confirm Okay');
            }
          }
        ]}
      />
    </IonContent>
  );
};

export default Tab1;

to add objects into the buttons array prop to add the buttons.

handler has the event handler that’s called when we click it.

cssClass has the class name.

text has the button text.

role has the button role.

Badge

We can add a badge with the IonBadge component.

For example, we can write:

import React from 'react';
import { IonBadge, IonContent } from '@ionic/react';
import './Tab1.css';

const Tab1: React.FC = () => {
  return (
    <IonContent>
      <IonBadge color="primary">11</IonBadge>
    </IonContent>
  );
};

export default Tab1;

to add the badge with the IonBadge component.

color has the color for the badge.

Button

We can add buttons to our Ionic React app with the IonButton component.

For example, we can write:

import React from 'react';
import { IonButton, IonContent } from '@ionic/react';
import './Tab1.css';

const Tab1: React.FC = () => {
  return (
    <IonContent>
      <IonButton color="dark">Dark</IonButton>
      <IonButton shape="round">Round Button</IonButton>
      <IonButton expand="full">Full Button</IonButton>
    </IonContent>
  );
};

export default Tab1;

to add the buttons.

color has the button background color.

shape has the button shape.

expand set to full means the button spans the whole screen’s width.

Conclusion

We can add alerts, buttons, and badges easily with Ionic React.

Categories
React Ionic

Mobile Development with Ionic and React — Routing

If we know how to create React web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with React.

Conditional Routing

We can make route components render conditionally.

To do that, we add the render prop to our route:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import {
  IonApp,
  IonIcon,
  IonLabel,
  IonRouterOutlet,
  IonTabBar,
  IonTabButton,
  IonTabs
} from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import { triangle } from 'ionicons/icons';
import Tab1 from './pages/Tab1';
import Bar from './pages/Bar';
import Foo from './pages/Foo';

/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';

const isAuth = true;

const App: React.FC = () => (
  <IonApp>
    <IonReactRouter>
      <IonTabs>
        <IonRouterOutlet>
          <Route path="/tab1" component={Tab1} exact={true} />
          <Route
            exact
            path="/random"
            render={props => {
              return isAuth ? <Foo /> : <Bar />;
            }}
          />
          <Route path="/" render={() => <Redirect to="/tab1" />} exact={true} />
        </IonRouterOutlet>
        <IonTabBar slot="bottom">
          <IonTabButton tab="tab1" href="/tab1">
            <IonIcon icon={triangle} />
            <IonLabel>Tab 1</IonLabel>
          </IonTabButton>
          <IonTabButton tab="random" href="/random">
            <IonIcon icon={triangle} />
            <IonLabel>Random</IonLabel>
          </IonTabButton>
        </IonTabBar>
      </IonTabs>
    </IonReactRouter>
  </IonApp>
);

export default App;

The render prop takes a function with the props as the parameter and we can return the component we want to render in the function.

Nested Routes

We can define nested routes with Ionic React.

To do that, we write:

App.tsx

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import {
  IonApp,
  IonIcon,
  IonItem,
  IonLabel,
  IonRouterOutlet,
  IonTabBar,
  IonTabButton,
  IonTabs
} from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import { triangle } from 'ionicons/icons';
import Tab1 from './pages/Tab1';
import DashboardPage from './pages/DashboardPage';

/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';

const App: React.FC = () => (
  <IonApp>
    <IonReactRouter>
      <IonTabs>
        <IonRouterOutlet>
          <Route path="/tab1" component={Tab1} exact={true} />
          <Route path="/dashboard" component={DashboardPage} />
          <Route path="/" render={() => <Redirect to="/tab1" />} exact={true} />
        </IonRouterOutlet>
        <IonTabBar slot="bottom">
          <IonTabButton tab="tab1" href="/tab1">
            <IonIcon icon={triangle} />
            <IonLabel>Tab 1</IonLabel>
          </IonTabButton>
        </IonTabBar>
      </IonTabs>
    </IonReactRouter>
  </IonApp>
);

export default App;

pages/DashboardPage.tsx

import { IonRouterOutlet } from '@ionic/react';
import React from 'react';
import { Route, RouteComponentProps } from 'react-router';
import Bar from './Bar';
import Foo from './Foo';

const DashboardPage: React.FC<RouteComponentProps> = ({ match }) => {
  return (
    <IonRouterOutlet>
      <Route exact path={match.url} component={Bar} />
      <Route path={`${match.url}/foo`} component={Foo} />
    </IonRouterOutlet>
  );
};

export default DashboardPage;

pages/Foo.tsx

import React from 'react';
import { IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';

const Foo: React.FC = () => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Foo</IonTitle>
        </IonToolbar>
      </IonHeader>
    </IonPage>
  );
};

export default Foo;

We added the:

<Route path="/dashboard" component={DashboardPage} />

to load the DashboardPage compoennt when we go to /dashboard .

In DashboardPage , we have more routes.

We have:

<Route path={`${match.url}/foo`} component={Foo} />

So we see the Foo component when we go to /dashboard/foo .

Conclusion

We can add various kind of routes with Ionic React.

Categories
React Ionic

Mobile Development with Ionic and React — Lifecycles and Routes

If we know how to create React web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with React.

Lifecycle Methods in Functional Components

Ionic for React comes with its own lifecycle hooks.

They include the useIonViewDidEnter, useIonViewDidLeave , useIonViewWillEnter , and useIonViewWillLeave hooks.

The useIonViewDidEnter hook is run when the ionViewDidEnter event is triggered.

It’s called every time the view is visible.

useIonViewDidLeave is called when the ionViewDidLeave event is triggered.

This event is triggered when the page is fully transitioned in.

Any logic that we might not normally do when the view is visible can go here.

The useIonViewWillEnter hook is called when ionViewWillEnter .

It’s called every time the component is navigated to.

The useIonViewWillLeave callback can be used to run cleanup code.

We can put them all in a component by writing:

pages/Tab1.tsx

import React from 'react';
import { IonButton, IonCol, IonContent, IonGrid, IonHeader, IonPage, IonRow, IonText, IonTitle, IonToolbar, useIonViewDidEnter, useIonViewDidLeave, useIonViewWillEnter, useIonViewWillLeave } from '@ionic/react';
import './Tab1.css';

const Tab1: React.FC = () => {
  useIonViewDidEnter(() => {
    console.log('ionViewDidEnter event fired');
  });

  useIonViewDidLeave(() => {
    console.log('ionViewDidLeave event fired');
  });

  useIonViewWillEnter(() => {
    console.log('ionViewWillEnter event fired');
  });

  useIonViewWillLeave(() => {
    console.log('ionViewWillLeave event fired');
  });

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Tab 1</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <IonGrid>
          <IonRow>
            <IonText>hello world</IonText>
          </IonRow>
        </IonGrid>
      </IonContent>
    </IonPage>
  );
};

export default Tab1;

React Navigation

We can add navigation to an Ionic React app with route components.

It comes with its own router to resolve the routes.

For example, we have:

App.tsx

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import {
  IonApp,
  IonIcon,
  IonLabel,
  IonRouterOutlet,
  IonTabBar,
  IonTabButton,
  IonTabs
} from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import { ellipse, square, triangle } from 'ionicons/icons';
import Tab1 from './pages/Tab1';
import Tab2 from './pages/Tab2';
import Tab3 from './pages/Tab3';

/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';

/* Theme variables */
import './theme/variables.css';

const App: React.FC = () => (
  <IonApp>
    <IonReactRouter>
      <IonTabs>
        <IonRouterOutlet>
          <Route path="/tab1" component={Tab1} exact={true} />
          <Route path="/tab2" component={Tab2} exact={true} />
          <Route path="/tab3" component={Tab3} />
          <Route path="/" render={() => <Redirect to="/tab1" />} exact={true} />
        </IonRouterOutlet>
        <IonTabBar slot="bottom">
          <IonTabButton tab="tab1" href="/tab1">
            <IonIcon icon={triangle} />
            <IonLabel>Tab 1</IonLabel>
          </IonTabButton>
          <IonTabButton tab="tab2" href="/tab2">
            <IonIcon icon={ellipse} />
            <IonLabel>Tab 2</IonLabel>
          </IonTabButton>
          <IonTabButton tab="tab3" href="/tab3">
            <IonIcon icon={square} />
            <IonLabel>Tab 3</IonLabel>
          </IonTabButton>
        </IonTabBar>
      </IonTabs>
    </IonReactRouter>
  </IonApp>
);

export default App;

We have the Route components in the IonRouterOutlet to add our route components.

path has the URLs, component has the component to show when we reach the route. exact set to true means we match the exact URL.

Then to add navigation buttons, we add the IonTabButton components with the href prop set to the URL for the paths.

Conclusion

We can add lifecycle hooks and routes with Ionic React.

Categories
React Ionic

Getting Started with Mobile Development with Ionic and React

If we know how to create React web apps but want to develop mobile apps, we can use the Ionic framework.

In this article, we’ll look at how to get started with mobile development with the Ionic framework with React.

Getting Started

We can get started by installing a few things.

First, we install the Ionic CLI globally by running:

npm install -g @ionic/cli native-run cordova-res

Next, we can create our Ionic app project by running:

ionic start ionic-app tabs --type=react --capacitor

tabs adds tabs to the app.

type set to react means we’ll create a React project

--capacitor means we add Capacitor so we can run and build a native app from our project files.

Then we run:

npm install @ionic/react-hooks @ionic/pwa-elements

in the ionic-app project folder to install the React hooks for our project.

Then to run the app in the browser, we run:

ionic serve

Running the App with Genymotion

To run our app with Genymotion and built a native app, we need to do more things.

First, we run:

ionic build

to create the assets folder.

Then we run:

npx cap add android
npx cap sync

to add the Android dependencies.

Then we need to install Android Studio and Genymotion.

After we install Android Studio, we install the Genymotion plugin for Android Studio.

Once we did that, we run:

ionic capacitor run android --livereload --external --address=0.0.0.0

to preview our app in Genymotion.

Now we should see the app reload live.

Creating a Camera App

We can create a camera app easily with Ionic.

To do this, we go to Tab1.tsx and write:

pages/Tab1.tsx

import React, { useEffect, useState } from 'react';
import { IonButton, IonCol, IonContent, IonGrid, IonHeader, IonImg, IonPage, IonRow, IonTitle, IonToolbar } from '@ionic/react';
import ExploreContainer from '../components/ExploreContainer';
import './Tab1.css';
import { useCamera } from '@ionic/react-hooks/camera';
import { CameraResultType, CameraSource } from "@capacitor/core";

interface Photo {
  filepath: string;
  webviewPath?: string;
}

function usePhotoGallery() {
  const { getPhoto } = useCamera();
  const [photos, setPhotos] = useState<Photo[]>([]);

  const takePhoto = async () => {
    const cameraPhoto = await getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera,
      quality: 100
    });

  const fileName = new Date().getTime() + '.jpeg';
    const newPhotos = [{
      filepath: fileName,
      webviewPath: cameraPhoto.webPath
    }, ...photos];
    setPhotos(newPhotos)
  };

  return {
    photos,
    takePhoto
  };
}

const Tab1: React.FC = () => {
  const { photos, takePhoto } = usePhotoGallery();

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Tab 1</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <IonGrid>
          <IonRow>
            <IonButton onClick={takePhoto}>take photo</IonButton>
          </IonRow>
          <IonRow>
            {photos.map((photo, index) => (
              <IonCol size="6" key={index}>
                <IonImg src={photo.webviewPath} />
              </IonCol>
            ))}
          </IonRow>
        </IonGrid>
      </IonContent>
    </IonPage>
  );
};

export default Tab1;

This is the code for the whole camera app.

We created the usePhotoGallery hook that uses the useCamera hook to call the getPhoto function to create the cameraPhoto object.

With it, the camera will show.

Then we add the newPhotos array to get the photo and put it in the photos array.

The webviewPath has the path of the photo.

In the Tab1 component, we added an IonButton to show the take photo button.

We set the onClick prop to the takePhoto function to show the camera and take the photo.

Then once we’re done taking the photo, we get the photos from the photos array and display them.

Conclusion

We can create a simple app with Ionic easily.

Categories
jQuery

jQuery — Widths and Wrapping

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.width()

The .width() method gets the current computed width for the first element in the set of matched elements or set the width of every matched element.

For example, we can write:

console.log($(window).width());

to log the width of the window.

To set the widths of the divs given the following HTML:

<div>d</div>  
<div>d</div>  
<div>d</div>  
<div>d</div>  
<div>d</div>

And CSS:

div {  
  width: 70px;  
  height: 50px;  
  float: left;  
  margin: 5px;  
  background: red;  
  cursor: pointer;  
}

We can add click handlers to the divs and change the width inside by writing:

const modWidth = 50;  
$("div").one("click", function() {  
  $(this).width(modWidth)  
});

.wrap()

The .wrap() method lets us wrap an element with a wrapper element.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap each div with the class inner with a div with class new by writing:

$(".inner").wrap("<div class='new'></div>");

.wrapAll()

The .wrapAll() method lets us wrap an HTML structure around all elements in the set of matched elements.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap a div with class new around all the divs with class inner by writing:

$(".inner").wrapAll("<div class='new' />");

.wrapInner()

We can wrap an HTML structure around the content of each element in the set of matched elements with the wrapInner method.

For example, if we have:

<div class="container">  
  <div class="inner">Hello</div>  
  <div class="inner">Goodbye</div>  
</div>

Then we can wrap the content of each div with class inner with a div with class new by writing:

$(".inner").wrapInner("<div class='new'></div>");

Conclusion

We can wrap elements with other elements with jQuery.

Also, we can get and set the width of the elements.