To use Onsen UI in React apps, Onsen UI Core and React Components should be installed to the project. These modules can be installed via NPM package: onsenui
and react-onsenui
.
To quickly setup the project, Monaca CLI will solve all dependencies including TypeScript, Webpack and polyfills if necessary.
$ npm install -g monaca # Install Monaca CLI - Onsen UI toolkit
$ monaca create helloworld # Choose React template
$ cd helloworld; monaca preview # Run preview, or "monaca debug" to run on your device
# The "react-onsenui" library requires the "onsenui" library.
$ npm install --save-dev onsenui react-onsenui
Onsen UI React Components Kitchensink contains almost all components in Onsen UI as one application package. Link to Kitchensink Demo.
The code in this example is transpiled using Babel and bundled with Browserify.
Onsen UI for React is an extension to Onsen UI core, a Web components based UI framework. You need to load the following two JavaScript modules.
You can load with a normal tag as follows:
<script src="react.js">script>
<script src="react-dom.js">script>
<script src="onsenui.js">script>
<script src="react-onsenui.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js">script>
Or, you can use React and Onsen UI from npm with CommonJS module system like Browserify or Webpack. In this case, use the onsenui
and react-onsenui
packages, in addition to react
and react-dom
npm packages. In the example below ons
contains Onsen UI core instance, and Ons
contains React components.
var React = require('react');
var ReactDOM = require('react-dom');
var ons = require('onsenui');
var Ons = require('react-onsenui');
Alternatively, you can also use ES6 imports to specify the modules you want to use in react-onsenui
package.
import {Page, Toolbar, Button} from 'react-onsenui';
To get started, let’s create a simple Hello World application. The following sample code is a React version of Onsen UI HelloWorld.
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/onsenui.css">
<link rel="stylesheet" href="css/onsen-css-components.css">
<script src="react.js">script>
<script src="react-dom.js">script>
<script src="onsenui.js">script>
<script src="react-onsenui.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js">script>
head>
<body>
<div id="app">div>
body>
<script type="text/babel">
var App = React.createClass({
handleClick: function() {
ons.notification.alert('Hello world!');
},
render: function() {
return (
Tap me!
);
}
});
ReactDOM.render( , document.getElementById('app'));
script>
html>
This example is loading the following JS libraries, react.js
, react-dom.js
, onsenui.js
and react-onsenui.js
. For stylesheets, it is loading onsenui.css
and onsen-css-components.css
which are bundled in Onsen UI distribution package. To know the details about Onsen UI stylesheets, please refer to our Style Sheets Guide document.
<link rel="stylesheet" href="css/onsenui.css">
<link rel="stylesheet" href="css/onsen-css-components.css">
In Also notice Inside the script, As you can see in this example, all Putting together, when This is a basic introduction of how Onsen UI and React works together. If you want to further learn React, we recommend to read the official React docs. The root of a page is created using the A toolbar is defined as a The toolbar is divided into 3 sections that can be specified as class names ( Onsen UI components are capable of handling events. For instance, you can catch a tap event by using the Onsen UI not only provides custom elements, it also exposes an object called The following example uses See also Simply use ES6 imports: For a full list of components please check the reference page. Onsen UI provides a rich set of form components. Apart from Lists are a very common pattern in mobile apps and thus Onsen UI provides abstraction for it. By using For cases when the list can contain thousands of items, Onsen UI provides a grid system to place your elements in the screen. The grid system divides the screen into rows and columns, just like a spreadsheet. The width and height of each grid is adjustable, and you can also condense two or more grids in a row or column, into one grid. The layout can be performed by combining Grid is not necessary in general for list items. Special layout is provided for list items based on flat iOS and Material Design specification. See list section for more information. Other components from different categories are available to complete the developer needs. A very common way to check for updates in apps is given by the Onsen UI bundles three icon packs to be used with In general, Ionicons are good for iOS apps while the Material Icons work best for apps using Material Design. It is a common use case to detect a finger gesture and do a specific task. Onsen UI utilizes a modified version of Hammer.js for gesture detection. The Gesture Detector class (Hammer.js) is exposed in If you want to use another library for this purpose and have any conflict, Onsen UI gesture detectors can be disabled easily: There are multiple types of dialog components available in Onsen UI: Apart from that, In Onsen UI there are three navigation patterns based on three different components: More information is provided in the “Docs” tab of the Live Example section of each component. The main pattern uses Use this pattern when you have a sequential flow where a page depends on the previous one. Data can be optionally passed from one page to another. In this case, by using A menu can be added using the Splitter provides two frames that can load different content: Modifier is a cross-component way to provide customizability for Onsen UI components. When a component is defined with a For example, each of the following buttons have different look. To change modifiers dynamically, please manipulate Onsen UI components are automatically styled depending on the platform where the app runs. You can easily test this feature with your browser Dev Tools by switching between iOS and Android views. Automatic styling simply applies Some tools are provided to give a more accurate customization. You can set a platform with With this, for example, you can display The second icon will be displayed when Onsen UI styles are defined in You can also use Onsen CSS Components to customize pre-defined colors. After the customization, you can download and replace to the existing If you want to apply a different style to a specific component, you can use For example, if you want to apply a thick border only to a specific button, you can define like the one below. Then, write the appropriate style code under the style tag or in the css file. tag, there is only a
app
id. This is where React will render the content into, and you can see it in the very bottom of JS code.
tag has
text/babel
type. This means this script is not a pure JavaScript that browser supports (most commonly ECMAScript5), but is a ECMAScript6 (ES2015) with JSX format. Babel will transpile this code into ES5 in the browser. To get better performance, we can use node.js to transpile the code.React.createClass()
function defines a React Component called App
. It has one method called render
, and this is the function that is called when the app is rendered. The returning object is described in JSX, which is a XML like language that extends JavaScript. In this case, it is returning
component that has an
component. The onClick
prop is used to call the handleClick
method when the user taps the button.return (
components are React Components, and they are loaded by react-onsenui.js
. Click here to see our full Onsen UI React Components Reference.index.html
is loaded into the browser, it will compile JSX code, inject into the body, and render the content.Creating a page
element. It covers the whole screen and is used as a container for the other elements.Adding a toolbar
or
component. Here is the typical example of a toolbar.<Page renderToolbar={() =>
<Toolbar>
<div className="left">
<BackButton>BackBackButton>
div>
<div className="center">Titlediv>
<div className="right">
<ToolbarButton>
<Icon icon="md-menu" />
ToolbarButton>
div>
Toolbar> }
>
Static page app
Page>
left
, center
, and right
). You can use
to display an icon,
or
to place an button, or insert any HTML content.Event Handling
onClick
prop, or text input change with the onChange
prop.class MyPage extends React.Component {
handleClick() {
ons.notification.alert('Hello, world!');
}
render() {
return() (
<Page>
<Button onClick={this.handleClick}>Click me!Button>
Page>
);
}
}
The
ons
objectons
with a lot of useful functions attached to it. The ons
object is part of the core library and can be imported in the bindings.ons.ready(fn)
which waits until the app is completely loaded before executing a callback function. Inside the callback, it is calling ons.notification.alert()
to display a alert dialog.ons.ready(function() {
// Onsen UI is now initialized
ons.notification.alert('Welcome to Onsen UI!');
});
ons.platform
, ons.notification
and ons.orientation
for more utilities.Importing
ons
object in Reactimport ons from `onsenui`;
import { platfrom, notification } from `onsenui`;
Adding page content
Form elements
,
and
, perhaps the component is the most common one since it supports different shapes:
checkbox
, radio
, password
, etc.value={this.state.text} float
onChange={(event) => { this.setState({text: event.target.value})} }
modifier='material'
placeholder='Username' />
"checkbox" checked={this.state.checked} onChange={this.onChange} />
Lists
,
and
you can make simple or complex lists of items. Every list item is by default divided into three sections, just like
, and some CSS classes are provided for default styles (list__item__icon
, list__item__thumbnail
, list__item__title
and list__item__subtitle
).<List
dataSource={['Row 1', 'Row 2']}
renderRow={(row, idx) => (
<ListItem modifier={idx === this.state.data.length - 1 ? 'longdivider' : null}>
<div className="left">
<Icon icon="md-face" className="list__item__icon" />
div>
<div className="center">
<span className="list__item__title">{row}span>
<span className="list__item__subtitle">Subtitlespan>
div>
<label className="right">
<Switch />
label>
ListItem>
)}
/>
Lazy repeat
component will enhance the performance by loading and unloading items depending on the current scroll.Layouting
and
components. The width and height can be adjusted in a flexible way.Control and visual components
Carousel
and
components provide a simple carousel that can optionally be overscrollable and fullscreen.Pull-hook
component, which enables a simple “pull to refresh” functionality.Speed-dial
and
are just a set of floating action buttons (
) that can be shown or hidden by the user. This components are mainly used in Material Design.Progress
and
display the loading progress like it’s done in Material Design. Two modes are supported: display the exact progress that is provided to the component or display an indeterminated progress.Icons
component:
fa-
ion-
md-
Gesture detector
ons.GestureDetector
object.var divGD = ons.GestureDetector(document.querySelector('#my-div'));
divGD.on('dragup dragdown', function(event) {
console.log('drag Y axis');
});
ons.GestureDetector(document.querySelector('#my-menu')).dispose(); // Remove event listeners from the menu
Dialogs
for displaying a page inside a centered dialog;
for displaying a simple message inside an alert style dialog;
for showing some content next to a specified element or a context menu; and
for displaying a fullscreen dialog that forbids user interaction.ons.notification
object offers a more handy solution for simple dialogs:ons.notification.alert('Hello world!'); // Basic alert
ons.notification.confirm('Are you ready?'); // OK - Cancel buttons
ons.notification.prompt('What is your name?'); // Text input
Multiple page navigation
,
and
. These components supply “frames” able to change their inner content. The content of these frames will normally be
components but it is also possible to nest navigation components in order to combine them.Navigator
component to provide a stack where you can push and pop pages with transition animations. This is the basic and most used navigation pattern and can be combined with the other two.Tabbar
component a visible tabbar is displayed at the bottom or the top of the page with tabs associated to different pages. The component will load content depending on the selected tab (
). This pattern is commonly used to sepparate different sections in the app.Menu
component. For small devices it can be used to create a swipeable menu, but for larger screens it can automatically display a column layout.
and
. A common usecase is to show a list in the side menu where each item loads a different page in the content frame. Notice that loading new content in any of these frames will completely remove the previous loaded content. For more complex navigation consider nesting
inside
.Using Modifier
modifier
, it will have a separate class namespace so that you can apply custom styles to the component. Also, some components have several preset modifiers to change the appearance.modifier
attribute from JavaScript.<Button modifier="quiet">QuietButton>
<Button modifier="light">LightButton>
<Button modifier="large">LargeButton>
<Button modifier="cta">Call To ActionButton>
<Button modifier="material">Material DesignButton>
Cross platform styling
modifier="material"
to the components when ons.platform.isAndroid()
is true. You can disable this feature by running ons.disableAutoStyling()
right after including onsenui.js
(i.e. before the app is initialized). If you disable it you may need to manually specify modifier="material"
in every component you want to display with Material Design. You can also specify disable-auto-styling
attribute in specific components that you don’t want to auto style.Platform utilities
ons.platform
object is available with methods such as ons.platform.isIOS()
, ons.platform.isWebView()
, etc.ons.platform.select('android')
, for example, in order to display Material Design on every platform. This must be called before the app is initialized (right after including onsenui.js
).
for Material Design and other type of button for iOS flat design.Icons shortcut
component provides a shortcut to make auto styling easier:<Icon icon="ion-navicon, material:md-menu" size="24px, material:20px" />
material
modifier is present (other modifiers can be used).CSS Definitions
onsenui.css
and onsen-css-components.css
. They are written in the Stylus format.onsenui.css
is a core CSS module that defines styles for the custom elements. The source code exists under core/css
directory. onsen-css-components.css
contains CSS definitions for CSS components. The source code exists in css-components/components-src/stylus
.onsenui-css-components.css
to reflect the changes.Overriding CSS style
modifier
attribute to override its style definition.<ons-button modifier="thick">Thick Buttonons-button>
<style>
.button--thick {
border: 10px;
}
style>