Apentle React native hints and tips

Manage React Native Theme

Manage React Native Theme

React Native helps me to build user interface faster and easier. But I have some problems:

  1. I often update my app style
  2. I want to style my app like I'm styling a website
  3. My users want to change theme in their app

Yes, this means we need a react native theme manager. In this post, I’ll show you how to do it. Now, let’s get started.

Libraries #

We are going to use two libraries for our react native project. They are:

  1. react-native-theme helps us to manage react native theme at compile time and runtime
  2. babel-plugin-react-native-css-class gives us another way to use StyleSheet in react native
  3. babel-preset-react-native helps us transform react native code

To install these libraries, go to our project directory and run this command:

npm i --save react-native-theme babel-plugin-react-native-css-class babel-preset-react-native

Now, we can start to use these libraries in our project.

Manage theme with react-native-theme #

At first, we need to register theme data in some fist lines of code in our project. May be in index.ios.js and index.android.js file. To remove duplicate in two files above, we can require a new file app.js. Our index.ios.js and index.android.js may look like:

'use strict';

const {AppRegistry} = require('react-native');
const app = require('./app');

AppRegistry.registerComponent('ThemeExample', () => app);

And app.js might be:

'use strict';

import React, {
  Component,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';
import theme, {styles} from 'react-native-theme';
const ThemeExample = require('./ThemeExample');

// Setup Themes

theme.add(require('./theme/default'));
theme.add(require('./theme/red'), 'red');

const App = React.createClass({
  getInitialState() {
    theme.setRoot(this);
    return null;
  },
  _defaultTheme() {
    if (theme.name !== 'default') {
      theme.active();
    }
  },
  _redTheme() {
    if (theme.name !== 'red') {
      theme.active('red');
    }
  },
  render() {
    return (
      <View class="container">
        <ThemeExample />
        <TouchableOpacity onPress={this._defaultTheme}>
          <View class="button default">
            <Text class="label">DEFAULT THEME</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={this._redTheme}>
          <View class="button red">
            <Text class="label">RED THEME</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
});

module.exports = App;

In this file, we should see two important lines:

theme.add(require('./theme/default'));
theme.add(require('./theme/red'), 'red');

These lines add theme data for our project. We have two themes called “default” and “red”. In this example, we will switch between two themes at runtime. Now, we look at the file theme/default.js:

'use strict';

const styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  header: {
    fontSize: 30,
    fontWeight: 'bold',
    margin: 10,
  },
  body: {
    margin: 10,
    alignItems: 'center',
  },
  content: {
    fontSize: 20,
  },
  strong: {
    fontWeight: 'bold',
  },
  button: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#4DC7A4',
    paddingHorizontal: 40,
    borderRadius: 25,
    width: 300,
    height: 50,
    overflow: 'hidden',
    margin: 10,
  },
  label: {
    margin: 10,
    fontSize: 23,
    color: '#FFF',
  },
  footer: {
    fontSize: 30,
    fontWeight: 'bold',
    margin: 10,
  },
  default: {
    backgroundColor: '#4DC7A4',
  },
  red: {
    backgroundColor: 'red',
  },
};

module.exports = styles;

That’s it. It only have styles data. Then, we look at the file ThemeExample.js, that uses styles from theme:

'use strict';

import React, {
  Component,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

import {styles} from 'react-native-theme';

class ThemeExample extends Component {
  render() {
    return (
      <View class='container'>
        <Text class="header">
          Header Title
        </Text>
        <View class="body">
          <Text class="content">
            <Text class="strong">react-native-theme</Text> helps you manage your application theme. Separate style files and switch theme at runtime...
          </Text>
          <TouchableOpacity>
            <View class="button">
              <Text class="label">OK</Text>
            </View>
          </TouchableOpacity>
        </View>
        <Text class="footer">
          Footer
        </Text>
      </View>
    );
  }
}

module.exports = ThemeExample;

And we see an important line import {styles} from ‘react-native-theme’;. This line makes us can use styles variant.

All the code above, we can see a strange attribute of react native component. How can we use it? Let’s take a look the next section.

Component class tag #

Yes, we use class tag usually when we’re styling our website. But in react native, it is a weird tag for a component. However we can use it with babel-plugin-react-native-css-class plugin. Before we use it, we need to configure our transform options via .babelrc in our project directory.

{
  "presets": [ "react-native" ],
  "plugins": [ "react-native-css-class" ]
}

This plugin will automatically transform our class tag to react native standard style tag. For example, our output of ThemeExample.js file will look like:

'use strict';

import React, { Component, Text, View, TouchableOpacity } from 'react-native';

import { styles } from 'react-native-theme';

class ThemeExample extends Component {
  render() {
    return <View style={styles.container}>
        <Text style={styles.header}>
          Header Title
        </Text>
        <View style={styles.body}>
          <Text style={styles.content}>
            <Text style={styles.strong}>react-native-theme</Text> helps you manage your application theme. Separate style files and switch theme at runtime...
          </Text>
          <TouchableOpacity>
            <View style={styles.button}>
              <Text style={styles.label}>OK</Text>
            </View>
          </TouchableOpacity>
        </View>
        <Text style={styles.footer}>
          Footer
        </Text>
      </View>;
  }
}

module.exports = ThemeExample;

Yeah! Now we can use class tag as the way we use in the website.

Conclusion #

Our example will run like this: React Native Theme Example

You can also download full source code from Github.

If you have any question, please leave a comment below. Thank you!

Two helpful testing tools for React Native

Two helpful testing tools for React Native

In the previous post, we introduced how to make a test for component in react native. Today, we introduce two tools to help you write testing code much easier. react-native-babel-jest help you to configure testing enviroment quickly and enzyme help you traverse your React Native Components’ output easier.

react-native-babel-jest #

react-native-babel-jest help you to configure testing enviroment quickly. First, install it to your project by command

npm i --save-dev react-native-babel-jest

Add the code below to your package.json file

{
  "scripts": {
    "test": "jest"
  },
  ...
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/react-native-babel-jest",
    "setupEnvScriptFile": "<rootDir>/node_modules/react-native-babel-jest/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "react",
      "promise",
      "source-map"
    ]
  }
}

The most important things on these code are scriptPreprocessor and setupEnvScriptFile. It will help you to setup testing enviroment. It includes react-native-mocking object, so you don’t need to mock it manually. Good sound! Let’s write a component ShowComponent.js like this

'use strict';

import React, {
  Component,
  StyleSheet,
  Text,
  View,
} from 'react-native';

class ShowComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.show}>
          Show Text
        </Text>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
  },
  show: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

module.exports = ShowComponent;

And make a test file ShowComponent-test.js in folder tests

'use strict';

const React = require('react-native');
const { View } = React;
const TestUtils = require('react/lib/ReactTestUtils');

jest.unmock('../ShowComponent');
const ShowComponent = require('../ShowComponent');

describe('<ShowComponent />', () => {
  it('Component must show "Show Text"', () => {
    // Shallow rendering

    const renderer = TestUtils.createRenderer();
    renderer.render(<ShowComponent />);
    let output = renderer.getRenderOutput();
    expect(output.type).toBe(View);
    // Deep render to DOM

    const dom = TestUtils.renderIntoDocument(<ShowComponent />);
    const txtNode = TestUtils.findRenderedDOMComponentWithClass(dom, 'Text');
    expect(txtNode.textContent).toBe('Show Text');
  });
});

Okay, run test command

npm test

and see the result

[ PASS ]  __tests__/ShowComponent-test.js (0.905s)

enzyme #

In the testing code above, we used ReactTestUtils to make a component test. But it’s hard to remember and write it. enzyme helps us to make a good deal with it. Let’s install it.

npm i --save-dev enzyme babel-preset-airbnb

Unmock enzyme module by adding code below to your package.json file

{
  "jest": {
    "unmockedModulePathPatterns": [
      "enzyme",
      ...
    ]
  }
}

Now, rewrite our testing code in file ShowComponent-test.js

'use strict';

import React, { View, Text } from 'react-native';
import { shallow, mount } from 'enzyme';

jest.unmock('../ShowComponent');
const ShowComponent = require('../ShowComponent');

describe('<ShowComponent />', () => {
  it('Component must show "Show Text"', () => {
    // Shallow rendering

    const output = shallow(<ShowComponent />);
    expect(output.type()).toBe(View);
    expect(output.find(Text).length).toBe(1);

    // Full DOM rendering

    const wrapper= mount(<ShowComponent />);
    expect(wrapper.find(Text).text()).toBe('Show Text');
  });
});

Run test and see the result like this

[ PASS ]  __tests__/ShowComponent-test.js (0.681s)

We can also test with user action. Let’s create an component ActionComponent.js like this

'use strict';

import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

class ActionComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {isOn: false};
    this._onPress = this._onPress.bind(this);
  }
  _onPress() {
    this.setState({isOn: !this.state.isOn});
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this._onPress}>
          <Text style={styles.button}>
            {this.state.isOn ? "On" : "Off"}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: 'red',
  },
  button: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

module.exports = ActionComponent;

And the test file ActionComponent-test.js in folder tests

'use strict';

import React, { Text, TouchableOpacity } from 'react-native';
import { mount } from 'enzyme';

jest.unmock('../ActionComponent');
const ActionComponent = require('../ActionComponent');

describe('<ActionComponent />', () => {
  it('Component response to user action', () => {
    // Full DOM rendering

    const wrapper = mount(<ActionComponent />);
    expect(wrapper.find(Text).text()).toBe('Off');
    // Simulate user tap

    wrapper.find(TouchableOpacity).simulate('click');
    expect(wrapper.find(Text).text()).toBe('On');
  });
});

Now, run the test and see the result

[ PASS ]  __tests__/ActionComponent-test.js (0.684s)

Conclusion #

I am looking at my testing code, it’s shorter and clearer. These tools help me to save my time. I hope it saves your time too. If you don’t want to type the code from this tutorial, just checkout from github. Thank you!

React Native Testing: Function, Component and Action

React Native Testing: Function, Component and Action

Testing is one of the most important parts in programming. You might need to test the function, component, action… Or you might use BDD/TDD to develop your app. This tutorial will help you to solve these problems, write the react native testing, step by step. Here we go!

Jest Tests #

Jest tests are JS-only tests run on the command line with node. At first, we need to install it by command.

npm i --save-dev jest-cli

Add the code below to your package.json file.

"scripts": {
  "test": "jest"
}

Now, you can run the testing with command.

npm test

This may output with “No tests found” message. We will write a sample function to test. Let’s make a file square.js

function square(x) {
  return x * x;
}
module.exports = square;

And make a test file square-test.js in folder tests

jest.unmock('../square');

describe('square', () => {
  it('3 square to equal 9', () => {
    const square = require('../square');
    expect(square(3)).toEqual(9);
  });
});

Run the testing command, you will see the output.

[ PASS ]  __tests__/square-test.js (0.036s)

Now, you know how to create an Jest test.

React Native Testing Component #

To test a React Native component, we will use the React library to render component. We also use babel to transform our component code while testing. At first, we need to install it.

npm i --save-dev babel-core babel-preset-jest babel-preset-es2015 babel-preset-react

Create a custom preprocessor called preprocessor.js to process testing for react native

'use strict';

const babel = require('babel-core');
const jestPreset = require('babel-preset-jest');
const es2015Preset = require('babel-preset-es2015');
const reactPreset = require('babel-preset-react');

module.exports = {
  process(src, filename) {
    if (babel.util.canCompile(filename)) {
      return babel.transform(src, {
        auxiliaryCommentBefore: ' istanbul ignore next ',
        filename,
        presets: [jestPreset, es2015Preset, reactPreset],
        retainLines: true,
      }).code;
    }
    return src;
  },
};

Configure the Jest by add code below to package.json

{
  "jest": {
    "scriptPreprocessor": "<rootDir>/preprocessor.js",
    "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "react",
      "promise",
      "source-map"
    ]
  }
}

React Native Component does not render to HTML DOM. So, we need a mock to do that. Create file react-native.js in folder mocks

'use strict';

const React = require('react');
const ReactNative = React;

// Simulate style creator

ReactNative.StyleSheet = {
  create: function create(styles) {
      return styles;
  }
};

// Create react native component helper

const NativeComponent = (type) => {
  return React.createClass({
    render() {
      var properties = {className: type};
      if (typeof this.props.onPress !== 'undefined') {
        properties.onClick = this.props.onPress;
      }
      Object.assign(properties, this.props);
      return (
        <div {...properties}>{this.props.children}</div>
      );
    }
  });
};

// Specific to list view

class ListView extends React.Component {
  static DataSource() {
  }
  render() {
    var properties = {className: "ListView"};
    Object.assign(properties, this.props);
    return (
      <div {...properties}>{this.props.children}</div>
    );
  }
}

// App Registry

class AppRegistry {
  static registerComponent () {
  }
}

ReactNative.View = NativeComponent("View");
ReactNative.ScrollView = NativeComponent("ScrollView");
ReactNative.Text = NativeComponent("Text");
ReactNative.TouchableOpacity = NativeComponent("TouchableOpacity");
ReactNative.TouchableHighlight = NativeComponent("TouchableHighlight");
ReactNative.TouchableWithoutFeedback = NativeComponent("TouchableWithoutFeedback");
ReactNative.TouchableNativeFeedback = NativeComponent("TouchableNativeFeedback");
ReactNative.ToolbarAndroid = NativeComponent("ToolbarAndroid");
ReactNative.Image = NativeComponent("Image");
// Add more... if you needed


ReactNative.ListView = ListView;
ReactNative.AppRegistry = AppRegistry;

module.exports = ReactNative;

Let’s create a show text component ShowComponent.js

'use strict';

import React, {
  Component,
  StyleSheet,
  Text,
  View,
} from 'react-native';

class ShowComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.show}>
          Show Text
        </Text>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
  },
  show: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

module.exports = ShowComponent;

Then create the test file ShowComponent-test.js in folder tests

'use strict';

const React = require('react-native');
const { View } = React;
const TestUtils = require('react/lib/ReactTestUtils');

jest.unmock('../ShowComponent');
const ShowComponent = require('../ShowComponent');

describe('<ShowComponent />', () => {
  it('Component must show "Show Text"', () => {
    // Shallow rendering

    const renderer = TestUtils.createRenderer();
    renderer.render(<ShowComponent />);
    let output = renderer.getRenderOutput();
    expect(output.type).toBe(View);
    // Deep render to DOM

    const dom = TestUtils.renderIntoDocument(<ShowComponent />);
    const txtNode = TestUtils.findRenderedDOMComponentWithClass(dom, 'Text');
    expect(txtNode.textContent).toBe('Show Text');
  });
});

Run the test command

npm test

And see the test result

[ PASS ]  __tests__/ShowComponent-test.js (0.548s)

React Native Testing Action #

React testing utility provide a “Simulate” to help us simulating the user actions. However, some of the actions in react native does not exist on “Simulate”. We need to mock it before testing, look at the mocks/react-native.js

if (typeof this.props.onPress !== 'undefined') {
  properties.onClick = this.props.onPress;
}

The code above helps us to match onPress on react native with onClick on “Simulate”. Let’s create an action component ActionComponent.js

'use strict';

import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

class ActionComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {isOn: false};
    this._onPress = this._onPress.bind(this);
  }
  _onPress() {
    this.setState({isOn: !this.state.isOn});
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this._onPress}>
          <Text style={styles.button}>
            {this.state.isOn ? "On" : "Off"}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: 'red',
  },
  button: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

module.exports = ActionComponent;

And the test file ActionComponent-test.js in folder tests

'use strict';

const React = require('react-native');
const TestUtils = require('react/lib/ReactTestUtils');

jest.unmock('../ActionComponent');
const ActionComponent = require('../ActionComponent');

describe('<ActionComponent />', () => {
  it('Component response to user action', () => {
    // Deep render to DOM

    const dom = TestUtils.renderIntoDocument(<ActionComponent />);
    const txtNode = TestUtils.findRenderedDOMComponentWithClass(dom, 'Text');
    expect(txtNode.textContent).toBe('Off');
    // Simulate user tap

    TestUtils.Simulate.click(TestUtils.findRenderedDOMComponentWithClass(dom, 'TouchableOpacity'));
    expect(txtNode.textContent).toBe('On');
  });
});

Then run the test and see the result.

Conclusion #

This tutorial is a little long. And I hope it is helpful for you to deal with react native testing. I put all these code together on this repository. You can check it out and run your own. Thank you!

What happens inside React Native

What happens inside React Native

In the previous post, we built “Hello World” app and learned some JavaScript code using React Native platform. But what happens in the low level code, in your native project? This tutorial will take a look into it.

Work with JavaScript Server

React Native allows you to debug your JavaScript code instantly when you make a change without rebuild your app. Because it provides two ways to load JavaScript code. The fist one, it loads from an external server. So you can change your code and then tell React Native to reload it. The second one is from app’s bundle. This option is usually used for production version. Look at the file AppDelegate.m in your iOS project, you will see some lines of code like this.

NSURL *jsCodeLocation;

/**
 - Loading JavaScript code - uncomment the one you want.
 *
 - OPTION 1
 - Load from development server. Start the server from the repository root:
 *
 - $ npm start
 *
 - To run on device, change `localhost` to the IP address of your computer
 - (you can get this by typing `ifconfig` into the terminal and selecting the
 - `inet` value under `en0:`) and make sure your computer and iOS device are
 - on the same Wi-Fi network.
 */

jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];

/**
 - OPTION 2
 - Load from pre-bundled file on disk. The static bundle is automatically
 - generated by "Bundle React Native code and images" build step.
 */

// jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                    moduleName:@"HelloWorld"
                                             initialProperties:nil
                                                 launchOptions:launchOptions];

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;

Before release your app, make sure you are using JavaScript from app’s resource. It’s very important!

React Native connects JavaScript and Native Code

Look deeper inside the code of React Native, we will learn how to make a native component works on JavaScript environment. The easiest way is to look into an React Native component. We have two Objective-C files.

#import "RCTBridgeModule.h"

@interface RCTVibration : NSObject <RCTBridgeModule>
@end
#import "RCTVibration.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation RCTVibration

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(vibrate)
{
  AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

@end

We can see two macros in here. RCT_EXPORT_MODULE will export your class to React Native module. And RCT_EXPORT_METHOD will export your method to React Native method. Then we can use it on JavaScript file.

'use strict';
import React, {
  ...
  NativeModules,
} from 'react-native';

class HelloWorld extends Component {
  render() {
    // Vibrate on render

    NativeModules.Vibration.vibrate();
    return (
      ...
    );
  }
}

Press Cmd+R while running your app in Simulator or shake your phone and select “Reload” menu. Then you can see the result.

JavaScriptCore

In this section, I will introduce about a library that makes RCT_EXPORT_MODULE, RCT_EXPORT_METHOD macros work. It’s JavaScriptCore by Apple. It helps us to answer two questions (1)How to run JavaScript in native code? and (2)How to export native code to use in JavaScript? With the first question, we will look at two classes: JSContext and JSValue. JSContext is a JavaScript execution environment, you use a JSContext object to evaluate JavaScript scripts. JSValue is a reference to a JavaScript value, you use a JSValue object to convert value between JavaScript and Objective-C. For example.

JSContext *context = [[JSContext alloc] init];
[context evaluateScript:@"var square = function(x) { return x * x }"];
JSValue *square = [context evaluateScript:@"square(10)"];
NSLog(@"Ten squared: %@", [square toNumber]);
NSLog(@"String: %@", [square toString]);

With the second question, we use an Objective-C block to export method for JavaScript. Yes, we will call a native method from JavaScript.

context[@"fullName"] = ^(NSString *firstName, NSString *lastName){
  return [NSString stringWithFormat:@"%@ %@", firstName, lastName];
};
NSLog(@"My full name: %@", [context evaluateScript:@"fullName('Doan', 'Nguyen')"]);

These are very simple codes to make us figure out how React Native works.

Conclusion

Because React Native is an open source framework, we can learn many things from it with source code :). When we use it to build an app, we can use only JavaScript code with many libraries or mix the native and JavaScript code for better performance. Is it a good deal? Let think about it.

Getting Started with React Native

A year ago, Facebook announced React Native. You can see many hybrid mobile app frameworks as PhoneGap, IONIC, Mobile Angular UI and so on. But what makes React Native different?

  1. Native components for your app. You won’t see the UIWebView wrapper although you are coding with JavaScript!
  2. Styling your app like CSS. Really, you can build the native app with your skill on web developing.
  3. Debugging tools instantly on your running app. So you can build and test your UI faster.

Otherwise, React Native also works with your existing native app. And you can write the wrapper to bridge from your native code to React Native JavaScript. So, start to learn it? Here we go.

Install React Native

This tutorial guides you to install React Native on an OS X computer. At first, we need to install Xcode 7.0 or higher. It’s also available on App Store. And then, we install React Native with this command:

curl -o- https://raw.githubusercontent.com/apentle/utilities/master/react-native/install | bash

That’s it! Now you can create your own app with React Native. Let’s go.

Hello React Native App

Run command to create your own app from terminal. Note that this command will create a project on your current directory.

react-native init HelloWorld

Then, you can build and run your app on iOS Simulator.

cd HelloWorld
react-native run-ios

After that, a Node.js server is running in terminal like this. React Native Running Server And Hello World app is running on iOS Simulator. Press Command+D then select Show Inspector. You can debug your UI instantly on running app. Amazing! React Native Hello World React Native Debugging Now, we will take a look into the code.

Code structure

The source code folder of your app will look like this. React Native File Structure Look into the file index.ios.js. These are some pieces of code. In the header, we will see the code line

'use strict';

This line will enable the strict mode in JavaScript. In this mode, you should write your code extractly, all previously accepted “bad syntax” will become to real errors.

import React, {
    AppRegistry,
    Component,
    StyleSheet,
    Text,
    View
} from 'react-native';

These lines import React Native’s components the we will use later in this file. Now we take a look into our component.

class HelloWorld extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

Our component “HelloWorld” extends from Component. We should focus on its render function. We see the JSX syntax on return command. It’s a JavaScript syntax extension that looks similar to XML. It helps you code your UI like a HTML code! These code also use style attribute for components to render. The style is declared below:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Yes, it looks quite close to CSS. It makes you easy to build and modify your UI. And the last line of code:

AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

This line will register your component with name ‘HelloWorld’, and React Native will use it to run on your native app. Now can edit some line on this file and see the result on iOS Simulator by press Command+D. Yes, you don’t need to rebuild your app!

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Hello World!
        </Text>
        <Text style={styles.instructions}>
          This is my first React Native app.
        </Text>
      </View>
    );
  }

And see the result: Hello World Edited Code Okay. That’s your fist simple app.

Conclusion

We have just taken a look with React Native. You should feel yourself about it. Is it really simple? And we have many things to do with it. We can also learn more React Native by its samples from GitHub. See you next time!