You are on page 1of 19

Onsen UI - Course Introduction

Onsen UI is a HTML5 based UI framework used for creating apps.

In this course we will learn:

 Ons Objects
 Creating a page using Onsen UI
 Onsen UI Components
 Handling Events and Dialog
 Modifiers and Cross Platform Utilities
 Page Navigation and Animation

Introducing Onsen
Consider a scenario, in which you want an app that runs on Android and IOS devices.

 You need to prepare source code for each platform


 Debug the code twice and maintain them separately

What if you further need to enhance your app from time to time? You will have to
continue maintaining different code bases.

How about having a single code base supporting multiple platforms? Sounds great,
doesn't it?

This is where Onsen comes to rescue. The best part is that, you can create the app in your
favourite framework.

Let us start the journey by creating your first Hybrid app.

What is Onsen ?
Onsen is a UI framework used in building Hybrid and Mobile Web apps.

 The same source code can be used in all the platforms.


 It is very user friendy and easy to use framework.
 It supports Javascript core, Angular 1.x , Angular 2 and ReactJS.
 It has built-in web components that makes the development process a lot easier.

In this course we will use ReactJS with Onsen UI. We will go through various built-in
component that helps in creating a basic app.

Why should we go for Onsen?

 Cross platform support - Onsen is compatible with Android 4.4.4+, iOS 8+, Chrome,
Safari
 Offers a lot of framework choices - Includes frameworks like Angular 1.x, Angular
2+, ReactJS, Vue.js, Meteor
 Open source and Easy to Learn - Offers ready-made components required to
develop apps with native look and feel
 Particularly Optimised for Mobile - No lag while running the apps and performs just
like the native apps.
 Monaca Toolkit - Helps creating Hybrid apps using Onsen UI with less effort. Monaca
has its own CLI and cloud IDE that helps in creating apps.

Installing Monaca CLI


 Download and install Node.js.
 Install Monaca cli using the command npm install -g monaca
 Create a new project called "MyOnsen" using the command monaca create MyOnsen
 Once the installation of Onsen is successful, you would see a project folder MyOnsen.
Now open MyOnsen folder and navigate to app.jsx file in src folder
 You can start coding your application in app.jsx.
 Once your app is ready, the same can be previewed in the browser by typing in the
command cd MyOnsen monaca preview
 To review the app in any mobile device, use the command monaca debug.

Try it out - Installing Monaca CLI


 You could try just the installation steps for Monaca using katacoda playground

 For coding in JSX and verifying the same in the browser, you may use onsen
playground

Write the following  Hello to you (Aloha oukou) code and view it in the browser.
var MyPage = React.createClass({
render: function() {
return (
<Ons.Page >
<p style={{textAlign: 'center'}}>
Aloha oukou</p>
</Ons.Page>
); }});
ons.ready(function() {
ReactDOM.render(<MyPage />, document.getElementById('app'));
});

Introducing Ons Objects


 Onsen makes it easy to code by providing few ready-made built-in functions that are
part of the core Onsen UI library.
 Onsen provides these built-in custom components and methods with specific
functionality.
 Some of them are ons.ready , ons.platform, ons.notification and ons.orientation.

Using Ons Objects


To use ons objects, use import to include them from onsenui library.

 ons.platform- This object is useful when there is a need to run a platform specific
code.
 ons.notifiations- This object provides you with a ready made popup dialog window
in the screen.

import ons from `onsenui`;


import { platform, notification } from `onsenui`;

 To use any of the components that are part of ons object, it is required to import ons


object first.
 To include any specific methods from the core library, you can do so by importing the
specfic method.
Ons Objects - Example
Some of the commonly used methods are:

 ons.ready() - This will execute once the app initilises and completly loaded
 disableAnimations() - This will disable all animations. Useful during testing
 enableAutoStyling() - The UI will render corresponding style based on the Platform of
the device.

We will see other commonly used methods in upcoming cards.

Enhance Your Page


Now that you are familiar with how to do the setup for Onsen UI and how to write a
simple Aloha oukou (Hello to you) code, let us enhance our page with some of
the onsencomponents like ons.page and ons.toolbar.

Page Creation using Onsen UI


Page and Component(s)

In Onsen, the whole page should be encoded within the <Page> component.

 This page component acts as a container for all the other components.
 You can use components like <Button>, <Toolbar> within <Page> component.

Page and associated props

 There are many props that can be used within a page component.
 The content present inside the page are scrollable. To make it fixed
use renderFixedprop
 Likewise, to add a toolbar to the page use renderToolbar prop
 To specify a particular content styling, use contentStyle
 onDeviceBackButton can be used for custom handler on device back button.

For complete list of props used, you can visit Onsen documentation


Toolbar Creation
<Toolbar> Component helps in creating Custom toolbars.

 It is used within the <Page> component. It is like a header to the page. In Android


devices, it displays as a material design toolbar.
 It can be rendered at the top or bottom (using <BottomToolbar>) of the page.
 It can include a button or a icon if required using corresponding built-in components.
 It mainly holds the side menu icon and the navigation icons like home, back etc.,

Page and Toolbar Creation - Example


Now, it is time to see page component and toolbar component in action.

Try running the following piece of code in : onsen.io playground

This example will render all the elements that are present within the <Page> component and a
toolbar with "Fresco Play" text inside the toolbar

var MyPage = React.createClass({


renderToolbar: function() {
return (
<Ons.Toolbar><div className='center'>FRESCO PLAY</div></Ons.Toolbar>
); },
render: function() {
return (
<Ons.Page renderToolbar={this.renderToolbar}>
<p style={{textAlign: 'center'}}>
WELCOME TO COURSE ON ONSEN UI </p>
</Ons.Page>
); }});
ons.ready(function() {
ReactDOM.render(<MyPage />, document.getElementById('app'));
});

Try it Out – Page Creation


By the end of this course, you will be creating a full-fledged Ticket Booking App.
As a first step, create the home page by adding a plain Home page and a tool bar to that
page as shown.

Use the Onsen Playground for this exercise: onsen.io playground

Components in Onsen UI
Onsen comprises of a wide set of form components. Some of them
are<Button>, <Fab>, <Switch>, <Range>, <Select>, <Input> and many more. We will study few
important, frequently used components in the upcoming cards.

Onsen also has custom UI elements that start with <ons.*>. They have attributes, methods,
properties and events just like the normal HTML elements, which can be used to access the
custom UI elements.

Button Component
 This component will render a button on the screen
 The styling will be selected based on the platform (iOS / Android / Chrome etc) automatically.
 Button components have to be embedded inside the <page> component only and cannot be
used in toolbar component.
 Incase the requirement is to add a button such as back, menu in toolbar, there are specific
components available in Onsen as per the required functionality.
 Button components can be customized and event handlers can be added to them using
corresponding props. (i.e. onClick, style etc.)

Example:
<Ons.Button style={{margin: '10px'}} onClick={this.handleClick}>Click
Me</Ons.Button>

Input Component
 Input is a widely used component. It helps in creating text boxes, check boxes, radio buttons
etc.
 By using the 'type' prop of this component, you can create any form elements.

Example:
<Ons.Input type='checkbox' /> <Ons.Input type='radio' /> <Ons.Input type='text' />
 You can also create event handlers within this component.

<Ons.Input type='radio' onChange={this.handleRadio}/>

 The appearance of the input can be customized by using modifiers on this component. We will
look at modifiers in subsequent cards.

Fab Component
 Fab stands for floating action button
 It is a circular button that is mostly displayed in bottom right corner of the app with specific
function.
 The position can be changed using the postion props to the left / center.
 More custom effects such as color changes, icons, ripple effect can be added using various
props that onsen offers with this component.

Example:

<Ons.Fab
style={{backgroundColor: ons.platform.isIOS() ? '#4182ab' : null}}
onClick={this.handleClick}
position='bottom left'>
<Ons.Icon icon='md-cloud' />
</Ons.Fab>

Select Component:
 This is used to render a drop down on a page.
 It supports all the props that a normal HTML select tag supports.
 Two important props are multiple and size.
 Multiple is used when more than one option needs to be selected.
 size decides the maximum number of options to be displayed, after that a scroll bar appears

Example:

<Ons.Select id="choices">
<option value="Samsung">Samsung</option>
<option value="Apple">Apple</option>
<option value="HTC">HTC</option>
</Ons.Select>

Switch Component
Switch element can be used to toggle between two states. The toggle can be done either by
tapping or dragging the element.

The checked prop is used to set the switch set to any one state by default.
Example:
<Ons.Switch checked={this.state.checked} onChange={this.handleSwitch} />  Gle can be
done either by tapping or dragging the element. The checked prop is used to set the switch
set to any one state by default.
Example:
<Ons.Switch checked={this.state.checked} onChange={this.handleSwitch} />

Components - Example

This example will render a basic form with all the form elements you have seen so far

//some code
render: function() {
return (
<Ons.Page renderToolbar={this.renderToolbar}>
<section style={{textAlign: 'center'}}>
<p><Ons.Input modifier='underbar' float placeholder='Username' /></p>
<p><Ons.Input modifier='underbar' type='password' float
placeholder='Password' /> </p>
<p> <Ons.Select id="choose-sel" >
<option value="option 1">Option 1</option>
<option value="moption 2">Option 2</option>
</Ons.Select></p>
<p><Ons.Input type='checkbox' float>Accept the terms and
conditions</Ons.Input></p>
< p>Keep me signed in</p>
<p><Ons.Switch/></p>
<p><Ons.Button onClick={this.handleClick}>Sign in</Ons.Button></p>
</section>
<Ons.Fab
style={{backgroundColor: ons.platform.isIOS() ? '#4282cc' : null}}
onClick={this.handleClickFab} position='bottom right'>
<Ons.Icon icon='md-face' /> </Ons.Fab>
</Ons.Page> ); }});
//some code

Dialog in Onsen UI
 Dialogs are pop-ups that enhance user interactions with the app
 Onsen offers a lot of options for dialog, the most commonly used dialog
being <Dialog> and <Alertdialog>. The functionality of both the components is same ie.,
displaying a pop-up message to the user. However, the animation and the styling associated
with them are different.
 Apart from this Ons.notifiction offers a wide variety of dialog such as conformation dialog with
ok and cancel button and prompt dialog Which can accept a input from user.

 Dialog – Example
 This example will show how to make use of various type of dialog boxes
 var MyPage = React.createClass({
 handleClickA: function() {
 ons.notification.alert('WELCOME TO COURSE ON ONSEN UI'); },
 handleClickC: function() {
 ons.notification.confirm('WELCOME TO COURSE ON ONSEN UI'); },
 handleClickP: function() {
 ons.notification.prompt('WELCOME TO COURSE ON ONSEN UI'); },
 renderToolbar: function() {
 return (
 <Ons.Toolbar> <div className='center'>FRESCO PLAY</div></Ons.Toolbar>
 ); },
 render: function() {
 return (
 <Ons.Page renderToolbar={this.renderToolbar}>
 <p style={{textAlign: 'center'}}>
 <Ons.Button onClick={this.handleClickA}>ALERT</Ons.Button>
 // code to render similar buttons

Try it Out – Form Creation


Let us add some functionality to the ticket booking app created in the previous module.

As shown, the app should have the following features:


 Input fields to take Start and Destination points
 Travel Date (as a drop-down list)
 Bus type (AC / Non-AC) (as radio buttons)
 Number of passengers (as range)
 Search tickets button

Page Life Cycle Events


<ons.Page> has events that will be fired at certain part of DOM life cycle. These events help in
performing certain functions.

 init : Is fired once the <Page> attaches to DOM. This is used only for initializing the app.
 destroy : Is fired after the <Page> detaches from DOM. This is used for memory clean up.
 show : This event is fired, once the <Page> comes to view,
 hide : This event is fired, once the <Page> moves out of the view but exists in memory.

Component Events

 Event handling process is similar to ReactJS


 The event handling props are mentioned using camelCase
 The event handlers are included within {}
 The commonly used handlers are onClick and onChange

This example will make use of onClick event of a button and show an alert message to the
user.

var MyPage = React.createClass({


handleClick: function() {
ons.notification.alert('WELCOME TO COURSE ON ONSEN UI'); },
//some code
render: function() {
return (
<Ons.Page renderToolbar={this.renderToolbar}>
<p style={{textAlign: 'center'}}>
<Ons.Button onClick={this.handleClick}>
START
</Ons.Button>
</p>
</Ons.Page> ); }});
//some code

Creating List
Let us consider an example that renders a list with two random names chosen from the array
'names' For each item present in the datasource array, a random name will be chosen and
rendered in <ListItem> component

//Some Code
renderRow: function(row, index) {
const names = ['Angular', 'ReactJS', 'Onsen'];
const name = names[Math.floor(names.length * Math.random())];
return (
<Ons.ListItem key={index}>
<div className='center'>
{name}
</div>
</Ons.ListItem>
); },
render: function() {
return (
<Ons.Page renderToolbar={this.renderToolbar}>
<Ons.List
dataSource={[ 1, 2]}
renderRow={this.renderRow}
renderHeader={() => <Ons.ListHeader>Welcome</Ons.ListHeader>} />
</Ons.Page> ); }});
//Some code

Creating Menu - Splitter Component


 In onsen, you can create a side menu using this component.
 Either it can be rendered as a column next to the main content or can be a swipe menu.
 The swipe menu is hidden from the view which is prefered in devices with small screen.
Apart from <Spliter>, two other components are needed to create a complete menu. They
are <SplitterSide> and <SplitterContent>.

SplitterSide Component
 This decides whether the menu is rendered as a column or a swipe menu
 The collapse property of this component is set to true to make it swipe
 You can make the menu accessable just by tapping instead of swiping using the
property isSwipeable
 The menu is opened and closed by setting isOpen property to true or false respectively
 onOpen & onClose property helps in executing any function once the menu is opended or closed
respectively

SplitterContent Component
The content that has to be displayed on screen beside menu should be included within this
component. A <Page> component should be present as a child component to this
component. The Hiearchy will be:

<Splitter>
<SplitterContent>
<Page>
//Content to be displayed
</Page>
</SplitterContent
</Splitter>

Creating Menu – Example

This will render a swipable menu in the screen with options that are created with list.

// some code
render: function() {
return (
<Ons.Splitter><Ons.SplitterSide
style={{
boxShadow: '0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)'}}
side='left' width={200} collapse={true} isSwipeable={true}
isOpen={this.state.isOpen} onClose={this.hide} onOpen={this.show}>
<Ons.Page><Ons.List
dataSource={['Angular', 'ReactJS', 'Onsen']}
renderRow={(title) => (
<Ons.ListItem key={title} onClick={this.hide}
tappable>{title}</Ons.ListItem>)} />
</Ons.Page> </Ons.SplitterSide>
<Ons.SplitterContent>
<Ons.Page renderToolbar={this.renderToolbar}>
<section style={{margin: '16px'}}>
<p>Swipe to open the menu</p>
</section>
</Ons.Page>
</Ons.SplitterContent>
</Ons.Splitter>
); }});
//some code

Try it Out – Adding side menu


Create a side menu in the tool bar of your Ticket Booking App from the earlier exercise and
as shown, add options such as

 Home
 Login
 Travel History
 Logout
 Settings
 Feedback
Creating List

 The <List> Component helps in creating list of items and render it on screen


 It makes use of renderRow and dataSource prop to create a list
 The renderRow prop must be set to a function that will
return <ListItem>component. <ListItem> contains the data that should be present in
the list
 dataSource prop should be set to an array with the required data

Preset-Modifiers
Modifiers help in styling your components.

 All built-in components have default Onsen styling


 In order to override these default styling, we use modifiers
 Some components have Preset Modifiers that provide a lot of choices for styling.

In this example, quiet and light are preset modifiers, that provide a different look to the


button.

<Ons.Button modifier="quiet">Quiet</ Ons.Button>


< Ons.Button modifier="light">Light</ Ons.Button>
Custom Modifiers
We can also style the components with custom modifiers.

In this example, red is a custom modifier that renders a red button in the screen.

< Ons.Button modifier="red">Red Button</ Ons.Button>

<style>
.button--red {
border: 10px;
color: red;
font-size: 16px;
}
</style>}

Cross Platform Utilities


 Onsen, by default, styles all the components based on the platform, be it android or
iOS or any supporting browser.
 The method ons.platform.isAndroid() will return true if the host is an android
device. Similarly ons.platform.isIOS() is used for ios devices.

 You can disable the autostyling of components based on platform. This can be done by
using ons.disableAutoStyling() and further go ahead with applying manual styling
using ons.platform.select('android').
 Whenever manual styling feature is used, it has to be called before the UI gets
initialized.

Cross Platform Utilities - Example


This will render fab button background based on the platform used :

<Ons.Fab
style={{backgroundColor: ons.platform.isIOS() ? '#4282cc' : null}}
onClick={this.handleClick}
position='bottom right'>
<Ons.Icon icon='md-face' />
</Ons.Fab>

Navigator Component
 The widely used navigation in mobile apps is Navigate component.
 It is a stack based navigation.
 All pages to be rendered are maintained in a stack and the page to be rendered is
pushed to the top using pushPage(route), where route is a parameter that has all the
information about the pages in stack.
 If the user decides to navigate to the previous page, then top page will be popped out
of the stack using popPage() and hidden from view.
 Navigator component has two properties:
o renderPage: The property is usually set to a function that will return a <page>
component

Tabbar Component
 Another commonly used navigation is the tabbar navigation. Pages are rendered
based on the tab selected.
 The tabbar component renders all the tabs and a page component is used to render
what to display when a tab is selected.
 The tabbar component makes use of three properties:
o index property to decide which page is currently visible
o onPreRender property which changes the index value on user tap
o renderTabs property which should have an array of objects which
includes content(has the content of the page) and tab(has information of the
page).

Animations using Onsen UI


Onsen makes use of Animit function to create custom animation for an element. Animit is a
library that handles the css transition.

You can use saveStyle() function to save the current animation of the element


before Animit modifies it. In case you want to restore the original animation,
use restoreStyle. Before using Animit function import it from ons library.

Animations - Example
This will add a custom animation for Element_1.

import { animit } from ons;


let animation1 = animit(Element_1)
//transiton code
animation1.play();

You can also modify an existing animation using extend function.

This will modify the defaulr fade-ios animation

var fadeIOS = ons.NavigatorElement.animators['fade-ios'];


var customAnimator = fadeIOS.extend({
//some code
})

Creating Animation using Onsen UI


Onsen UI allows you to create animation right from scratch.

Every component in Onsen has a set of animation interface buit-in, such as:

 NavigatorTransitionAnimator
 AlertDialogAnimator
 DialogAnimator
 PopoverAnimator
 ModalAnimator
 TabbarAnimator
 SplitterAnimator

They can be tweaked to your own desire and create a custom animation of your own.

Try it Out – Adding Navigation


Let us go back to our Ticket Booking App.

Now that you have a form to search buses of your choice, on clicking Search button, the user
should navigate to another page which displays the details of the buses available for booking
as shown.

User should be able to navigate to the previous page.


Onsen UI Course Summary
By now, you would have understood

 What is Onsen UI- What are Ons objects


 Usage of <Page> and <Toolbar> components
 Creating List and Menu items
 Usage of Various Components
 Creating Dialog Popups
 Handling Events
 Usage of Modifier
 Page Navigation
 Animations

Quiz :
1. Onsen supports only react Framework F
2. Onsen is used in building ________ apps. HYBRID
3. The function that executes after the app initializes ONS.READY()
4. Onsen helps in creating mobile apps using ______ JAVASCRIPT, CSS, HTML5
5. Ons object needs to be imported from the library ONSENUI
6. Onsen uses different source code for different Platforms. F
7. Onsen uses _______ CLI for Developing apps MONACA
8. Any HTML code can be placed inside the <Toolbar> component?T
9. The <ToolBar> component will render a toolbar at the _____ of the page Top
10. Switch element can have more than two states ? F
11. Which notification will accept user input? DIALOGUE
12. <Range> is one of the form Components? T
13. The switch element can be toggled using tab or drag : T
14. The prop that helps in creating check box and radio button: input
15. Onsen supports full screen dialog boxes: T
16. The prop that decides maximum number of items to be displayed in drop down :SIZE
17. You should use only the Onsen form Components for creating apps? F
18. How many sections does a toolbar have? 4
19. Which of the following is the correct way of specifying an event handler onClick
20. onChange is a event related to : <input> and <Select>
21. The unclose and on Open events are related to the component : all the options
22. The prop that decide whether a menu is swipe menu or not isSwipable
23. To disable swipe feature in a menu you should set false to : isSwipable
24. To open a menu set true to the prop: isOpen
25. The unclose and on Open events are related to the component : <SplitterSide>
26. To create a menu the required components are: all the options
27. You can set a platform styling manually with _______ ons.platform.select()
28. The default modifier for android devices is : materialDesign
29. The stack pages are initialized using : initialRoute
30. The component that helps in adding a heading to a list : <ListHeader>
31. The onClose and onOpen events are related to the component : <SplitterSide>
32. When a component state data changes, we can use : this.setState
33. The function that helps in making fab button Non-scrollable? renderFixed
34. The ons.platform,select() should be called after the app initializes completely: FALSE
35. <Navigator> component follows _____ based navigation : stack
36. Fab button can only be rendered in bottom-right or top-left side of page? TRUE
37. Onsen has its own CLI environment? FALSE
38. A carousel animation can be specified using : animation
39. The prop that decide whether a menu is a swipe menu or not? collapse
40. Which of the following is the Event that is related to Input textbox? onChange
41. The icon families available in onsen are: all the options
42. The <BackButton> component should be placed outside the <ToolBar> component: FALSE
43. The ______ property should be set to a function that returns a <Page> component : initialRoute
44. The <Carosal> component can render content horizontally and vertically: TRUE
45. Which one of the following is not a built in animation interface : SwipeAnimator
46. _____ helps in popping the top page of the navigator. PopButton
47. Arbitrary inputs of components are called: Props
48. The component that cannot be present inside the <Page> component is? None
49. Manual styling is done using : ons.platform.select()
50. The prop that decides whether a dialog can be cancelled : isCancelable
51. Which of the following is not a ons.platform object? None
52. Component can be declared as a function or class : TRUE
53. Use disable-auto-styling attribute for components to disable auto style: T

You might also like