Why choose React to create hybrid mobile apps?

Source: Internet
Author: User

"Editor's note" the author is the 14islands co-founder and creative Web developer David Lindkvist, who focuses on all aspects of hybrid application building. The article is a domestic ITOM management platform OneAPM compiled rendering.

Recently, we were fortunate to work with Fjord to create a HMTL5 hybrid application for its users from scratch.

Hybrid mobile apps (Hybrid apps) can build applications with a variety of web technologies and package them as native apps (Native apps) to suit a variety of mobile platforms.

In this article, we will analyze the technologies and challenges that are used when creating IOS and Android apps using React and Cordova.

Note: React Native in 2015. However, at the beginning of this project, React Native the Android version has not been released, so we cannot use it.

Challenges in hybrid applications

Hybrid mobile apps are nothing new. At the same time, it is certainly not the master key for all applications. The real challenge is to achieve the ultimate experience of the original application, with smooth animations and a sleek user interface.

In the past, with more traditional JavaScript MVC frameworks such as backbone.js, we have done many adventures and attempts in this direction.

Most hybrid applications start with a fast, responsive user interface. After that, it was easy to hit the south wall. This usually occurs at the end of the project, where, after several weeks of effort, the project has added a lot of functionality, and the content in the DOM is becoming richer.

At this point, the relationship between the view components becomes very difficult to trace, and the loop dependency of the event listener leads to excessive DOM read and write operations.

Enter React

React is a library of JavaScript functions that are used to create a user interface, often expressed as V (view) in MVC.

React knows to re-render based on the state of the component, and to save a virtual DOM for efficient re-rendering. This is great because when we write our code it's like we're re-rendering the entire template, and actually React only updates the DOM that has changed.

JSX

The biggest difference between React and common frameworks is that JavaScript logic and Markup (markup) templates are written in the same file using JSX syntax.

class MyTitle extends Component {  render() {    return (      

It takes a little time to adapt to this change. But once mastered, you will be able to greatly increase your productivity.

Mixins Duel Composition

I am a fan of modern JavaScript, preferring to write ES2015 syntax using Babel.

Mixins cannot be used with ES2015, for this reason. So, we choose higher-order-components (higher-order components) to create feature features instead of Mixins:

/** * Exports a higher order component wrapping the component to decorate * @param ComponentToDecorate the component which will be decorated */ export const withDecoratedData = ComponentToDecorate =>   class extends Component {    constructor() {            this.state = { data: null };    }    componentDidMount() {            this.setState({ data: ‘Decorated hello!‘ });    }    render() {            return <ComponentToDecorate {...this.props}  data={this.state.data} />;    }  }

You can then use the ES2016 adorner (Decorator) to apply the component. We can choose to enable the ES2016 adorner in Babel.

import {withDecoratedData} from ‘...‘;// Decorate component using ES7 decorator ‘@‘@withDecoratedDataclass MyComponent extends Component {  render() {        return <div>{this.data}</div>;  }}

In this way, we are connecting the view component with our Datastore (data stores).

Unidirectional Data Flow

For an application, the view layer is just the surface-the part behind the surface is the intricacies of the situation. React can be used in conjunction with most other frameworks to enable rendering of existing data models. However, the problem of large-scale MVC applications and cyclic dependencies persists, so Facebook has introduced a Flux design model with "unidirectional data flow" to make data flow easier to foresee.

The way Flux is implemented is numerous. After studying some of the cases, we selected alt.

UI Styles and animations

In order for the app to be as close to native as possible, the UI animation reaches 60 frames per second, and no flicker is critical. The JavaScript performance of the mobile browser has always been remarkably slow, so we make sure that only pure CSS animations and transformations are used.

inline style vs. CSS

Recently, the React world was a very enthusiastic topic: whether to use inline styles, that is, to set the style inside the element style properties, not using CSS.

To be honest, I prefer CSS, not very cold on the inline style. CSS is very clear about the importance of content, and as a web developer, we already know how to effectively apply responsive web design principles (responsive principles) to support different device performance and screen sizes.

The biggest controversy with inline styles is that "state" is largely a matter of JavaScript concern. Many times, we need to change the style according to the dynamic situation. However, if you think about it you will find that it is a perfect way to propagate state changes by adding or removing modifier classes.

BEM loves React

I prefer to write most styles using Saas with a slightly modified BEM class naming convention. We modified the BEM block name to match the camelcased JavaScript class name, thus implementing a clear combination of JavaScript and CSS for each component.

class MyComponent {  render() {    const activeClass = this.props.active ? ‘MyComponent--active‘ : ‘‘;        return (      <div className={"MyComponent " + activeClass}>        

This can be messy and cumbersome for components with many state modifiers. To this end, I created my own bem-helper to simplify the use of BEM class names in JSX.

import BEM from ‘bem-helper-js‘;class MyComponent { render() { return ( <div className={BEM(this).is(‘active‘, this.props.active)}> 

It will automatically get the block name from the JavaScript class name and, this.props.active is true as the true case may be, the following class name will be rendered:

<div class="MyComponent MyComponent--active"> 

Animating with React

For those of you who are accustomed to manually adding classes or modifying styles, this part may be a little acclimatized. The reality is that we have to take a step back and let React handle all the updates to the DOM.

Most animation libraries will have direct access to the DOM, so choose carefully.

Fortunately, the React team has provided us with the reactcsstransitiongroup to help solve common scenarios such as applying animation classes, adding and subtracting animated elements in the DOM. In our application, it effectively handles page conversions.

Closure

We used Apache Cordova to package apps and build IOS and Android versions. Its settings are fairly straightforward and provide a number of useful plugins that enable native functionality through a JavaScript API.

For example, we include the Statusbar plugin, which changes the color of the native status bar at run time.

Starting with IOS 8, we can finally set up scrolling events during the inertia scrolling phase, which is the continuous scrolling action after the touch stops. older versions of UIWebView do not support this feature, and Cordova uses the legacy UIWebView by default.

For IOS 9 users expect the Wkwebview engine, the official provides a Cordova plugin. However, if CORS is not enabled, XHR cannot be used through the FILE://protocol.

Summarize

We are pleased with our choice of using React to complete this project. However, we still have some notable places to make adjustments next time.

Advantage

    • Improved rendering performance--react enables efficient DOM updates
    • Simplifying the authoring of reusable components
    • Powerful JSX syntax for combining data with tag templates
    • Once the system decision is reached and the component is reused, productivity can increase
    • Avoid direct access to the DOM by developers (i.e., the risk of reducing damage performance)

Disadvantages

    • If you do not modify the DOM directly, it is difficult to use the React state to animate the timeline complex
    • Not a comprehensive solution-inexperienced developers are hard to get started with. Need to select a Router, Flux library or data layer, etc.
    • The new React release is more frequent and the ecosystem is not mature enough-most plugins change more frequently than React, and the API
      has been changing. In this project, we react-router Alt have encountered a fault-type API change in both. Alt
      The changes are particularly rapid and the documentation is not up-to-date. In the next React project, we will focus on Redux.
Where to go next?

Now, React Native is gaining momentum and is worth further tracking. The key difference is that it has a proxy layer between JavaScript and the native SDK. It runs JavaScript code in a separate thread, so it also guarantees smooth animations when performing other operations. In addition, with the Flexbox method, the React Native also selects inline styles rather than CSS. It is estimated that more than 85% of the code base between IOS and Android can be shared.

This article is compiled and presented by OneAPM engineers. OneAPM Browser Insight is a real user-based Web front-end performance monitoring platform that can help you locate site performance bottlenecks, website acceleration effect visualization, browser support, App browsing HTML and HTML5 pages. To read more technical articles, please visit the OneAPM Official technology blog.

This article was transferred from OneAPM official blog

Original address: http://14islands.com/blog/2016/03/03/why-we-chose-react-for-hybrid-app/

Why choose React to create hybrid mobile apps?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.