Sample Mobile Application with React and Cordova


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.


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 = (employee) {
                return (
                    <EmployeeListItem key={} employee={employee} />
            return (
  • 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.


  • Jeremy

    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? :)

  • Hamund

    @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.

  • 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.

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

      • Batuta

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

      • Carlos


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


    • Mio

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


    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?

  • Pingback: 簡單玩 React | Duncan 's blog()

  • Thank you share..

  • Pingback: Animated Page Transitions with React.js | Christophe Coenraets()

  • Pingback: Employee Directory Sample App with React and Node.js | Christophe Coenraets()

  • Pingback: Building Salesforce Apps with React.js | Christophe Coenraets()

  • Pingback: Belgian Beer Explorer with React, Bootstrap, Node.js and Postgres | Christophe Coenraets()

  • 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.

  • Pingback: About React | 懒得折腾()

  • Johnny H.

    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.

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

  • Pingback: 久々にCordova (旧PhoneGap) 触ってみた | はなたんのブログ()

  • Tuba Libre

    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.

  • Pingback: 学习笔记 Cordova+AmazeUI+React 做个通讯录 – 准备 | Macworks Collection()

  • Pingback: ReactJS: Links And Resources (3) | Angel "Java" Lopez on Blog()

  • Tremayne

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

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

  • It looks nice but doesn’t work

  • Pingback: Mobile Web Weekly No.35 | ENUE()


  • Thanks for the article!
    Cordova is great..
    I’ll definitely try this out

  • subbu boyapati

    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?

  • Pingback: 20 Resources and tutorials about ReactJS framework - JS-Republic's Blog()

  • Rudi Bloes

    I would like to get started with Cordova on Mac. But I can not even get it installed properly. It works a little bit but errors are blowing around my head. Been at this for weeks now, and it’s a mess, please help me. Here’s my question on stack overflow:
    and the story of the trouble installing the configuration: