Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Read Minds with React Native

Gigi Sayfan shows you how great React Native is at reading your mind by building a simple native application demo.


advertisement

Facebook's React.js view framework is a huge success. It is component-based, has one way binding and is super fast. The awesomeness just oozes out of it. But, what about all those phones out there? Fear not. React Native takes the React.js model and applies it to iOS and Android.

React Native is different from other frameworks. It exposes the same component-based model as React.js, but it is not embedding a browser wrapped in a thin native wrapper. A React Native application is indeed a native application using the native OS components and has access to its APIs. This is very powerful and yet the programming mode has the familiar React look and feel. You style your views with stylesheets, you layout your views using flexbox and you can manage your data using Flux if you wish.

Today, I'm going to show you how great React Native is by reading your mind. The Mind Reader sample React Native application displays five cards and lets you pick one (just by thinking about it). Once you picked a card Mind Reader will remove the card you picked. Amazing, I know. You can find an online version and the code in the React Native Playground.



Note, that I worked on the Android version only, but with small changes an iOS version can also be created.

Setting up the Development Environment

I developed Mind Reader in two environments: the online ReactiveNative Playground (http://rnplay.org) and locally using the genymotion simulator. The online playground is very easy and convenient, but I ran into some issues and debugging cab be fairly difficult. The local development environment requires a non-trivial amount of ceremony, but if you're already a mobile developer you probably have most of the pieces in place. Installing React Native itself is just a couple of terminal commands. Follow the full instructions here.

Getting Started

To start the project you go to a directory and type:


react-native init MindReader

This will create a whole project structure with separate files for iOS and Android including build and testing support.

You can structure your application across multiple files and directories (it's highly recommended for non-trivial applications with many components). For the purpose of this article I kept everything in the main file: index.android.js.

The Code

Right at the beginning there is some boilerplate and all the React Native elements you use in your application. The AppRegistry is a must (and probably the View as well).


/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';


var React = require('react-native');
var {
    AppRegistry,
    Image,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    } = React;

Then, we have a couple of images for the cards that will be displayed.


var image_1 = 'http://i.imgur.com/s7HgkYg.png'
var image_2 = 'http://i.imgur.com/6XCmYus.png'

The next part is the MindReader React component. In this demo I used a single component. In full-fledged React applications there are usually many components nested within each other. I'll go over the code function by function.

First is getInitialState(), which is called once (think constructor). The state of the component here is very simple. There is a single boolean called 'cardPicked;, which is initially false.


var MindReader = React.createClass({
    getInitialState: function() {
        return { cardPicked: false, }
    },

The render() function is where most of the action is. Based on the state of cardPicked. It renders either a view that shows an image of five cards and asks the user to pick a card or a view with four cards saying that the program removed the picked card. You can see that various React Native elements are used in the construction of the views. The TouchableOpacity element is actually a button that has an 'onPress' callback function that's being called when it is pressed. The views are styled using style sheets I'll show later.


    render: function () {
        if (this.state.cardPicked)
        {
            return (
                <View style={styles.container}>
                    <Text style={styles.instructions}>Very good. I
have removed the card you picked.</Text>
                    <Image style={styles.image} source={{uri: image_2}} />
                </View>);
        } else {
            return (
                <View style={styles.container}>
                    <Text style={styles.instructions}>Pick a card. In your
                        head.</Text>
                    < Image style={styles.image} source={{uri: image_1}}/>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={this.onCardPick.bind(this)}>
                        <Text style={styles.buttonText}>I picked a card</Text>
                    </TouchableOpacity>
                </View>);
        }
    },

The onCardPick() function is called when the button is pressed. It is super simple and just sets the cardPicked state variable to true.


  onCardPick: function() {
    this.setState({cardPicked: true})
  },

});

The styles stylesheet controls the look and feel of the application (not going to win any prizes)


var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
  instructions: {
    fontSize: 30,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },

 image: {
   borderWidth: 1,
   width: 414,
   height: 346,
   padding: 10,
 },

 button: {
    textAlign: 'center',
    color: '#cccccc',
    marginBottom: 7,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'blue',
    borderRadius: 2,
    padding: 5,
 },

 buttonText : {
    fontSize: 30,
    color: '#333333',
 },
});


Finally, the application must be registered with the AppRegistry


AppRegistry.registerComponent('ReactNativeDemo', () => MindReader);

Conclusion

React Native is a very slick way to create a native mobile application using an almost cross-platform framework and a web programming model.



   
Gigi Sayfan is the chief platform architect of VRVIU, a start-up developing cutting-edge hardware + software technology in the virtual reality space. Gigi has been developing software professionally for 21 years in domains as diverse as instant messaging, morphing, chip fabrication process control, embedded multi-media application for game consoles, brain-inspired machine learning, custom browser development, web services for 3D distributed game platform, IoT/sensors and most recently virtual reality. He has written production code every day in many programming languages such as C, C++, C#, Python, Java, Delphi, Javascript and even Cobol and PowerBuilder for operating systems such as Windows (3.11 through 7), Linux, Mac OSX, Lynx (embedded) and Sony Playstation. His technical expertise includes databases, low-level networking, distributed systems, unorthodox user interfaces and general software development life cycle.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date