devxlogo

Read Minds with React Native

Read Minds with React Native

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 (                                    Very good. Ihave removed the card you picked.                                    );        } else {            return (                                    Pick a card. In your                        head.                                                                I picked a card                                    );        }    },

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist