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.                    < Image style={styles.image} source={{uri: image_1}}/>                                            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.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as