Sample Mobile Application with React and Cordova

react

I recently spent some time playing with React, Facebook’s JavaScript framework for building user interfaces. The term “UI Framework” means different things to different people: In the case of React, it’s a framework that makes it easy to build and compose UI components; it is not a library of out-of-the-box UI components.

Some key characteristics of the React:

  • No templates: Components are the building blocks. By keeping the markup and the corresponding UI logic together, you have the full power of JavaScript to express the UI. More on this here.
  • JSX syntax allows you to inline the declarative description of the UI in your JavaScript code. React translates JSX to plain JavaScript on the fly (suitable during development), or offline using the React CLI.
  • Virtual DOM. In React, rendering a component means creating a lightweight description of the component UI. React diffs this new description with the old one (if any), and generates a minimal set of changes to apply to the DOM.

The Sample App

Nothing like building an app to get familiar with a new language or framework. In this article, I share a React version of the Employee Directory app that I’ve used to explore other frameworks.

Thinking in React” encourages us to start with a mockup of the UI, and break it down into a component hierarchy.

uimockscript

Based on this diagram, the component hierarchy for the Employee Directory app looks like this:

- App
    - HomePage
        - Header
        - SearchBar
        - EmployeeList
            - EmployeeListItem
    - EmployeePage
        - Header
        - EmployeeDetails


“App” is the application container that will transition pages in and out of the UI. Only one page is displayed at any given time.

Source Code

In this article, we will build the application going through several iterations, from a simple static prototype to the final product. The source code for the application, including the different iterations and a Cordova version, is available in this repository.

If you plan to run the application locally, you need to load it from a local web server, not from the file system.

Iteration 1: Static Version

In this first version, we create and render the HomePage component with some hardcoded (static) sample data.

View source | Run it

Code Highlights:

  • Creating components is easy: You use React.createClass(), implement the render() function, and return the UI description.
  • The JSX returned by render() is not an actual DOM node: it’s a description of the UI that will be diffed with the current description to perform the minimum set of changes to the DOM.
  • JSX is optional: you can use the React APIs to create the UI description programmatically.
  • Composing components is easy: You can use a component created using React.createClass() as a tag in JSX. For example, HomePage is made of three other components: Header, SearchBar, and EmployeeList.

Iteration 2: Data Flow

In this second version, we define an array of employees in the HomePage component, and we make the data flow down the component hierarchy to EmployeeList and EmployeeListItem. In this version, the list of employees is hardcoded: we’ll work with dynamic data in iteration 4.

View source | Run it

Code Highlights:

  • In JSX, you can add attributes to your custom component tags to pass properties to the component instance.
    <EmployeeList employees={employees}/>
    
  • Properties passed by the parent are available in this.props in the child. For example EmployeeList can access the list of employees provided by HomePage in this.props.employees.
  • In a list component (like EmployeeList), it’s a common pattern to programmatically create an array of child components (like EmployeeListItem) and include that array in the JSX description of the component.
        render: function () {
            var items = this.props.employees.map(function (employee) {
                return (
                    <EmployeeListItem key={employee.id} employee={employee} />
                );
            });
            return (
                <ul>
                    {items}
                </ul>
            );
        }
    
  • The key attribute (like in EmployeeListItem above) is used to uniquely identify an instance of a component (useful in the diff process).

Iteration 3: Inverse Data Flow

In the previous version, the data flew down the component hierarchy from HomePage to EmployeeListItem. In this version, we make data (the search key to be specific) flow upstream, from the SearchBar to the HomePage where it is used to find the corresponding employees.

View source | Run it

Code Highlights:
In this version, the inverse data flow is implemented by providing the child (SearchBar) with a handler to call back the parent (HomePage) when the search key value changes.

<SearchBar searchHandler={this.searchHandler}/>

Iteration 4: Async Data and State

In this version, we implement employee search using an async service. In this sample app, we use a mock in-memory service (defined in data.js) that uses promises so you can easily replace the implementation with Ajax calls. We keep track of the search key and the list of employees in the HomePage state.

View source | Run it

Code Highlights:

  • The state (this.state) is private to the component and is changed using this.setState().
  • The UI is automatically updated when the user types a new value in SearchBar. This is because when the state of a React component is changed, the component automatically re-renders itself (by executing its render() function).
  • getInitialState() executes once during the component lifecycle and and is used to set up the initial state of the component.

Iteration 5: Routing

In this version, we add an employee details page. Because the application now has more than one view, we add a simple view routing mechanism.

View source | Run it

Code Highlights:
There are many options to implement routing. Some routing libraries are specific to React (check out react-router), but you can also use other existing routing libraries. Because the routing requirements of this sample app are very simple, I used a simple script (router.js) that I have been using in other sample apps.

  • componentDidMount() is called when a component is rendered.

Iteration 6: Styling

Time to make the app look good. In this version, we use the Ratchet CSS library to provide the app with a mobile skin.

View source | Run it

Code Highlights:

  • Notice the use of className instead of class

Iteration 7: Maintaining State

If you run iteration 6, you’ll notice that when you navigate back to HomePage from EmployeePage, HomePage has lost its state (search key and employee list). In this version, we fix this problem and make sure the state is preserved.

View source | Run it

Code Highlights:

To keep track of the state, we introduce a new parent container (App) that maintains the state (searchKey and employee list) of the Home page and reloads it when the user navigates back to the Home Page.

Running in Cordova

The react-cordova folder in the repository provides a preconfigured Cordova project for the React version of the Employee Directory application.

 

29 Responses to Sample Mobile Application with React and Cordova

  1. Jeremy December 2, 2014 at 11:15 pm #

    Hey Chris, it’s been a while, glad you are making the switch to reactjs too, It’s like going back to the lovely flex framework era, right? :)

  2. Hamund December 3, 2014 at 2:25 am #

    @Jeremy, agree with you. Finally the rendering performance of single page apps in the browser is on the level that Flex provided 10 years ago(!) Thanks to React. This is needed to compete with native apps.

  3. Raymond Camden December 3, 2014 at 12:05 pm #

    I noticed in iteration 6, the online demo, you do *not* get a list of employees until you type a char and then backspace. This was in Firefox.

    • Christophe Coenraets December 3, 2014 at 12:10 pm #

      Hey Ray. Yes, that was by design (only show search results as opposed to starting with full list), but could easily be changed.

      • Batuta February 24, 2015 at 11:36 pm #

        Could you show a quick example of what to change to have the list retrieved on the onset?

      • Carlos August 10, 2015 at 3:21 pm #

        Christophe,

        Great tutorial – quick question though – how do we get all the employees to show by default?

        Thanks!

    • Mio May 13, 2015 at 11:57 pm #

      please help me!
      when i add new wine it was error but i tested everything is ok. (slim-wine-cellar-demo-app-master)

  4. VINAY December 4, 2014 at 3:44 am #

    I am following your blog and sample application with different frameworks. When I heard about the new framework, I visit your blog.

    Could you suggest a better combination of frameworks for business apps with morderate development efforts and less maintance in future?

  5. Cilt Bakımı December 5, 2014 at 2:27 am #

    Thank you share..

  6. Pierce Primm February 12, 2015 at 8:15 pm #

    Chris, I am new to React and have been reviewing examples/tutorials for a few weeks; even though the beginner may not have been your target audience. This is the best tutorial I have ever seen to initially learn how to do use React. Your formula for stepping through Iterations to introduce and explain concepts is UNBEATABLE. I wish this was the first one I reviewed. Thanks for putting it together.

  7. Johnny H. May 17, 2015 at 7:24 am #

    If you are running against cordova 5.0.0, you need to add the whitelist plugin and whitelist the tel: sms: and mailto: protocols:

    In config.xml:

    And add this plugin: cordova-plugin-whitelist 1.0.0 “Whitelist”

    • Johnny H. May 17, 2015 at 7:25 am #

      access origin=”tel:*” launch-external=”yes”
      access origin=”mailto:*” launch-external=”yes”
      access origin=”sms:*” launch-external=”yes”

  8. Tuba Libre September 8, 2015 at 10:38 am #

    You really create header twice instead making a reusable component?

    Forgive me, but this looks like bad practice.

    In general the way how ReactJS deals with markup is a shame and at least for me it doesn’t sell… The advantage of a virtual DOM (also with an eye on performance in some situations) does not cover the disadvantages of this approach for me. But maybe i’m wrong. Maybe control over markup and DOM is over-estimated as well as maintainability and separation of code, layout and design.

    Not everything Facebook does is good. And for me React JS is really a bad thing.

  9. Tremayne October 20, 2015 at 3:20 pm #

    Can you explain how you are using Deferred and Promise in the data.js file? What are the dependencies?

  10. forma imalatı November 17, 2015 at 8:43 am #

    Ткани, которые мы используем в нашей форме; Первый класс микро-блокировки; Flex-форме, антибактериальный, имеет термо-баланс, и сразу же сушки. Это дает вам свободу, чтобы переместить трикотажные изделия футбола в матче; Он предназначен стильный достаточно, чтобы носить на ежедневной основе. Наши модели выпускаются в двух типах, как мои специальных трикотажных изделий и другой цифровой распечатать.
      Его высокая производство нашей компании, мы используем спортивные носки продукты: хлопок, хлопок, полиэстер, нейлон и лайкра. Она включает в себя антибактериальные.

  11. çelik raf November 19, 2015 at 1:46 am #

    It looks nice but doesn’t work

  12. sohbet December 8, 2015 at 5:07 pm #

    VERY NİCE TO BLOG

  13. James February 14, 2016 at 4:03 am #

    Thanks for the article!
    Cordova is great..
    I’ll definitely try this out
    Regards
    James
    http://www.tilogeo.com

  14. subbu boyapati May 26, 2016 at 6:39 am #

    Hi when i navigate between two to three user profiles and when i click back all pages are in stack. How to avoid stack here?

Trackbacks/Pingbacks

  1. 簡單玩 React | Duncan 's blog - December 5, 2014

    […] 官網: React 教學: Reactjs 30 天邊做邊學系列 React Lessons Learning React.js: Getting Started and Concepts Sample Mobile Application with React and Cordova […]

  2. Animated Page Transitions with React.js | Christophe Coenraets - December 15, 2014

    […] exploring React in my previous post, I started experimenting with ways to implement animated page transitions in mobile web and […]

  3. Employee Directory Sample App with React and Node.js | Christophe Coenraets - December 19, 2014

    […] couple of weeks ago, I shared an Employee Directory sample application built with React in seven steps. Employee directory is a […]

  4. Building Salesforce Apps with React.js | Christophe Coenraets - December 29, 2014

    […] my previous posts, I shared several examples built with the React framework: I demonstrated how to build a React application in 7 steps, how to implement animated page transitions for mobile apps, and how to build a React application […]

  5. Belgian Beer Explorer with React, Bootstrap, Node.js and Postgres | Christophe Coenraets - January 6, 2015

    […] for a step-by-step walkthrough, take a look at the Employee Directory application I documented here and […]

  6. About React | 懒得折腾 - April 30, 2015

    […] Sample mobile application with react and cordova http://coenraets.org/blog/2014/12/sample-mobile-application-with-react-and-cordova/ […]

  7. 久々にCordova (旧PhoneGap) 触ってみた | はなたんのブログ - June 16, 2015

    […] Sample Mobile Application with React and Cordova | Christophe Coenraets […]

  8. 学习笔记 Cordova+AmazeUI+React 做个通讯录 – 准备 | Macworks Collection - September 25, 2015

    […] 正好最近认识了一群小伙伴,所以干脆做个通讯录吧。正好在网上搜到一篇《Sample Mobile Application with React and Cordova》,也是做的通讯录,边学就边做了。整个这篇文章都是在讲 React 的,所以其实可以当作 React 的入门教程。它所有的工作都在 www 目录中完成了,只需要通过浏览器就可以运行和简单的调试了,不过需要个 Web 服务器。 […]

  9. ReactJS: Links And Resources (3) | Angel "Java" Lopez on Blog - October 14, 2015

    […] Sample Mobile Application with React and Cordova | Christophe Coenraets http://coenraets.org/blog/2014/12/sample-mobile-application-with-react-and-cordova/ […]

  10. Mobile Web Weekly No.35 | ENUE - November 28, 2015

    […] Sample Mobile Application with React and Cordova […]

Leave a Reply

css.php