Build Mobile App With React

If you know JavaScript and are willing to develop a mobile app, React Native provides us with the ability to ship mobile apps with world-class user experience. Native app development targets  a specific OS, like Android and iOS. Such development needs individual code base for each platform. Unlike native development, React Native helps developers reuse code across the platforms. Let’s go ahead and get the basic idea of React Native and build a simple application.

What is React Native?

React Native is a new way to build mobile apps. It’s a cross platform JavaScript framework created by Facebook. It allows developers to use JavaScript to create mobile apps for both Android and iOS with native look and feel.

  • React Native is a JavaScript framework for building native mobile apps.
  • Uses React framework.
  • Offers a large number of inbuilt components and APIs to create UI and handle native features.

Prerequisites

  • Solid JavaScript knowledge as it’s based on JavaScript framework.
  • Understanding of ES6 as React native uses ES6 syntax extensively. Don’t sweat it, you can understand required concepts form this blog.
  • Basic understanding of React JS. If you don’t know also it’s fine, you can learn while working on the application.

Advantages

  • JavaScript
    You can leverage your existing JavaScript knowledge to build mobile apps.

  • Code Sharing
    You can share most of your code (~90%) across different platforms.

  • Fast development
    One of the key benefits of React native is shorter development time. React native shares major code and you can potentially save time & money.

  • Easy reloading
    Don't recompile the application each time a change has been made. Just press Cmd+R to reload or refresh the app in the simulator, emulator or device.

  • Community
    React native is open source and the community around the React native is large.

Let’s get started and build a simple mobile app using React native. The final screen of the app will look something like below screenshot.

React

In this app, we end up building online shopping search page which will show all products listed. We can search different products by category or typing the product name in the search bar.

Let’s start with the installation.

Installation

React native installation is straightforward.

Step 1

Install Node JS. Please browse through this link and download Node JS (version > 6.0)

Step 2

Go to your command prompt and use npm to install the create-react-native-app. Run Command line – npm install -g create-react-native-app

Step 3

Run the following command to create a new project called “SampleApp”

  • create-react-native-app SampleApp
  • cd SampleApp
  • npm start

This will start a development server and print a QR code in the terminal.

React

Step 4

Press any option you like to launch the app. I am choosing “a” as I am using Android emulator. Now you should able to see your first screen of the app.

React

Project Structure

After successful installation, we are good to go and can change or add code.

In the below screenshot we can see the folder structure of a newly created React native project.

Project Structure

React
 
Open the App.js file and change the existing text with any other verbiage and relaunch to make sure changes are reflecting properly.
  1. import React, {  
  2.     Component  
  3. } from 'react';  
  4. import {  
  5.     StyleSheet,  
  6.     Text,  
  7.     View  
  8. } from 'react-native';  
  9. export default class App extends Component {  
  10.     render() {  
  11.         return ( < View style = {  
  12.             styles.container  
  13.         } > < Text > Hello React native! < /Text> < /View>);  
  14.     }  
  15. }  
  16. const styles = StyleSheet.create({  
  17.     container: {  
  18.         flex: 1,  
  19.         backgroundColor: '#fff',  
  20.         alignItems: 'center',  
  21.         justifyContent: 'center',  
  22.     },  
  23. });  

As IDE, I am using Visual Studio Code but any other JavaScript editor can be used for developing React native code.

This is the output after changing the App.js file

React

Debugging

Press cmd + M (Android) and cmd + D (iOS) when app is open in the simulator/emulator. This will end up opening a dialog with different development menu.

React

To reload the app, we can choose “Reload” from the options or we can use keyboard cmd + R (iOS) and tap R twice (Android).

To debug the JavaScript code in the Chrome (browser), select “Debug JS Remotely” from the development menu. After choosing the option, a Chrome window will be opened in a new tab at http://localhost:8081/debugger-ui. Here in the below screenshot, we can see the Chrome developer tool sources tab lists all application files. We can put the break point and debug the code.

React

Build Application

Let’s go ahead and start implementation.

To design UI of the list page, we need a couple of controls to be imported from React-native library. I am importing all of them (TextInput, FlatList, Image, Picker, TouchableHighlight).

  1. import React, {  
  2.     Component  
  3. } from 'react';  
  4. import {  
  5.     StyleSheet,  
  6.     Text,  
  7.     TextInput,  
  8.     FlatList,  
  9.     Image,  
  10.     Picker,  
  11.     TouchableHighlight,  
  12.     View  
  13. } from 'react-native';  
  14. export default class App extends Component {  
  15.     render() {  
  16.         return ( < View style = {  
  17.             styles.container  
  18.         } > < Text > Hello React native! < /Text> < /View>);  
  19.     }  
  20. }  
  21. const styles = StyleSheet.create({  
  22.     container: {  
  23.         flex: 1,  
  24.         backgroundColor: '#fff',  
  25.         alignItems: 'center',  
  26.         justifyContent: 'center',  
  27.     },  
  28. });  
We need a local database where we put details of all products. I have created a JavaScript array of objects which will work as a database. ProductList is the array which is holding a bunch of objects and each object has six properties: key, name, price, category, imageUrl and CTYPE (categroty type).
  1. import React, {  
  2.     Component  
  3. } from 'react';  
  4. import {  
  5.     StyleSheet,  
  6.     Text,  
  7.     TextInput,  
  8.     FlatList,  
  9.     Image,  
  10.     Picker,  
  11.     TouchableHighlight,  
  12.     View  
  13. } from 'react-native';  
  14. var ProductList = [{  
  15.     key: 1,  
  16.     name: "Apple iPhone 7 Plus (Jet Black, 128GB)",  
  17.     Price: "Rs. 80,200",  
  18.     Category: "Mobile",  
  19.     imageUrl: require('./images/51Cqn38lCEL.jpg'),  
  20.     CTYPE: "M"  
  21. }, {  
  22.     key: 2,  
  23.     name: "Apple iPhone 6s (Space Grey, 32GB)",  
  24.     Price: "Rs. 40,200",  
  25.     Category: "Mobile",  
  26.     imageUrl: require('./images/71c8c5OWqgL._SL1500_.jpg'),  
  27.     CTYPE: "M"  
  28. }, {  
  29.     key: 3,  
  30.     name: "Samsung Galaxy On8 (Gold, 3 GB RAM + 16 GB Memory)",  
  31.     Price: "Rs. 13,000",  
  32.     Category: "Mobile",  
  33.     imageUrl: require('./images/71mtqsPn0HL._SL1500_.jpg'),  
  34.     CTYPE: "M"  
  35. }, {  
  36.     key: 4,  
  37.     name: "G-Shock Analog-Digital Black Dial Men's Watch - GA-1100-2ADR(G597)",  
  38.     Price: "Rs. 12,009",  
  39.     Category: "Watch",  
  40.     imageUrl: require('./images/910C9-8r6+L._UL1500_.jpg'),  
  41.     CTYPE: "W"  
  42. }, {  
  43.     key: 5,  
  44.     name: "Fastrack New OTS Analog Black Dial Men's Watch",  
  45.     Price: "Rs. 1,500",  
  46.     Category: "",  
  47.     CTYPE: "Watch",  
  48.     imageUrl: require('./images/81r-yEx3I6L._UL1500_.jpg'),  
  49.     CTYPE: "W"  
  50. }, {  
  51.     key: 6,  
  52.     name: "Tommy Hilfiger Men's Cool Sport Analog Display Quartz Blue ",  
  53.     Price: "Rs. 10,000",  
  54.     Category: "Watch",  
  55.     imageUrl: require('./images/91-DKgb4KdL._UL1500_.jpg'),  
  56.     CTYPE: "W"  
  57. }, {  
  58.     key: 7,  
  59.     name: "Fossil Machine Chronograph Black Dial Men's Watch",  
  60.     Price: "Rs. 7,995",  
  61.     Category: "Watch",  
  62.     imageUrl: require('./images/81Op2jBEg8L._UL1500_.jpg'),  
  63.     CTYPE: "W"  
  64. }, {  
  65.     key: 8,  
  66.     name: "boAt Rockerz 510 Wireless Bluetooth Headphones (Black)",  
  67.     Price: "Rs. 1,919",  
  68.     Category: "HeadPhone",  
  69.     imageUrl: require('./images/71FUKZe4cfL._SL1500_.jpg'),  
  70.     CTYPE: "H"  
  71. }, {  
  72.     key: 9,  
  73.     name: "Sony Extra Bass MDR-XB650BT Wireless Headphones (Blue)",  
  74.     Price: "Rs. 6,900",  
  75.     Category: "HeadPhone",  
  76.     imageUrl: require('./images/51ivKj0Wt6L._SL1000_.jpg'),  
  77.     Category: "H"  
  78. }, {  
  79.     key: 10,  
  80.     name: "Sennheiser HD 4.40-BT Bluetooth Headphones (Black)",  
  81.     Price: "Rs. 10,990",  
  82.     Category: "HeadPhone",  
  83.     imageUrl: require('./images/41Ooz6Kj8fL.jpg'),  
  84.     CTYPE: "H"  
  85. }];  

Next we are binding the product list to the FlatList. Here we can see the react specific terms like props and state. You can get the details of it from this URL. For now,

  • Props
    Properties are passed to a component and can hold data. But this cannot be changed inside components.

  • State
    State is used to refresh or update values in the component. Each time When “setState” method is called, the render() function in the Component will be called simultainously.
Here we are assigning the poduct list as state and setting it as data of FlatList fetching it from the state.
  1. export default class ListApp extends Component {  
  2.     constructor(props) {  
  3.         super(props);  
  4.         this.state = {  
  5.             type: "A",  
  6.             lvDataSource: ProductList  
  7.         }  
  8.     }  
  9.     render() {  
  10.         return ( < View style = {  
  11.                 styles.container  
  12.             } > < FlatList data = {  
  13.                 this.state.lvDataSource  
  14.             }  
  15.             keyExtractor = {  
  16.                 (item, index) => 'list-item-${index}'  
  17.             }  
  18.             renderItem = {  
  19.                 ({  
  20.                     item  
  21.                 }) => < View style = {  
  22.                     {  
  23.                         flex: 1,  
  24.                         flexDirection: 'row',  
  25.                         alignItems: 'center'  
  26.                     }  
  27.                 } > < Image source = {  
  28.                     item.imageUrl  
  29.                 }  
  30.                 style = {  
  31.                     {  
  32.                         width: 40,  
  33.                         height: 40,  
  34.                         margin: (0, 5, 0, 5)  
  35.                     }  
  36.                 }  
  37.                 /> < View > < Text style = {  
  38.                     {  
  39.                         width: 300,  
  40.                         color: 'darkblue'  
  41.                     }  
  42.                 } > {  
  43.                     item.name  
  44.                 } < /Text> < Text style = {  
  45.                     {  
  46.                         color: 'brown',  
  47.                         fontWeight: 'bold'  
  48.                     }  
  49.                 } > {  
  50.                     item.Price  
  51.                 } < /Text> < /View> < /View>  
  52.             }  
  53.             /> < /View>);  
  54.     }  
  55. }  
So far so good and this is the product list.
React

Now we have product list on screen and we would like to search required product and add a header image.

We need to implement text input and picker callbacks to filter out product from the list. OnChange event for text input and onValueChange event for picker needs to be handled filtering products based on typed text in the text input or selected value from the picker. This is the implementation with code snippet.

  1. export default class ListApp extends Component {  
  2.     constructor(props) {  
  3.         super(props);  
  4.         this.state = {  
  5.             type: "A",  
  6.             lvDataSource: ProductList  
  7.         }  
  8.     }  
  9.     _onTextChanged = (e) => {  
  10.         var SearchedList = [];  
  11.         var enteredText = e.nativeEvent.text;  
  12.         var selectedType = this.state.type;  
  13.         if (selectedType == "A") {  
  14.             SearchedList = ProductList.filter(function(product) {  
  15.                 return (product.name.toLowerCase().indexOf(enteredText.toLowerCase()) > -1);  
  16.             });  
  17.         } else {  
  18.             SearchedList = ProductList.filter(function(product) {  
  19.                 return (product.CTYPE == selectedType && product.name.toLowerCase().indexOf(enteredText.toLowerCase()) > -1);  
  20.             });  
  21.         }  
  22.         this.setState({  
  23.             lvDataSource: SearchedList  
  24.         });  
  25.     }  
  26.     _onValueChanged = (v, i) => {  
  27.         this.setState({  
  28.             type: v  
  29.         });  
  30.         if (v == "A") {  
  31.             this.setState({  
  32.                 lvDataSource: ProductList  
  33.             });  
  34.         } else {  
  35.             var selectedList = ProductList.filter(function(product) {  
  36.                 return (product.CTYPE == v);  
  37.             });  
  38.             this.setState({  
  39.                 lvDataSource: selectedList  
  40.             });  
  41.         }  
  42.     }  
  43.     render() {  
  44.         return ( < View style = {  
  45.                 styles.container  
  46.             } > < View > < Image source = {  
  47.                 require('./images/estore.jpg')  
  48.             }  
  49.             /> < Text style = {  
  50.                 {  
  51.                     fontWeight: 'bold'  
  52.                 }  
  53.             } > Search by: < /Text> < Picker selectedValue = {  
  54.                 this.state.type  
  55.             }  
  56.             onValueChange = {  
  57.                 this._onValueChanged  
  58.             } > < Picker.Item label = "All Category"  
  59.             value = "A" / > < Picker.Item label = "Mobile"  
  60.             value = "M" / > < Picker.Item label = "Watch"  
  61.             value = "W" / > < Picker.Item label = "Head phones"  
  62.             value = "H" / > < /Picker> < TextInput style = {  
  63.                 {  
  64.                     height: 45,  
  65.                     width: 800  
  66.                 }  
  67.             }  
  68.             onChange = {  
  69.                 this._onTextChanged  
  70.             }  
  71.             placeholder = "Type here to search!" / > < /View> < FlatList data = {  
  72.                 this.state.lvDataSource  
  73.             }  
  74.             keyExtractor = {  
  75.                 (item, index) => 'list-item-${index}'  
  76.             }  
  77.             renderItem = {  
  78.                 ({  
  79.                     item  
  80.                 }) => < View style = {  
  81.                     {  
  82.                         flex: 1,  
  83.                         flexDirection: 'row',  
  84.                         alignItems: 'center'  
  85.                     }  
  86.                 } > < Image source = {  
  87.                     item.imageUrl  
  88.                 }  
  89.                 style = {  
  90.                     {  
  91.                         width: 40,  
  92.                         height: 40,  
  93.                         margin: (0, 5, 0, 5)  
  94.                     }  
  95.                 }  
  96.                 /> < View > < Text style = {  
  97.                     {  
  98.                         width: 300,  
  99.                         color: 'darkblue'  
  100.                     }  
  101.                 } > {  
  102.                     item.name  
  103.                 } < /Text> < Text style = {  
  104.                     {  
  105.                         color: 'brown',  
  106.                         fontWeight: 'bold'  
  107.                     }  
  108.                 } > {  
  109.                     item.Price  
  110.                 } < /Text> < /View> < /View>  
  111.             }  
  112.             /> < /View>);  
  113.     }  
  114. }  
Let’s see how it’s working in action.

There we go, based on search text black the product list is filtered accordingly.

React

Let’s search by category as well. As Watch is selected from the picker, all watches are listed.

React

Great! We completed a sample application which is listing a bunch of products and searching/filtering them. Code attached along with this blog, you can download and go through.

This is the basic application to jump-start React native.

Every technology has certain downsides and React native is not an exception. So, before choosing React native for our project we need to consider those points as well,

  • It is good for building less responsive apps like social, e-commerce, data-entry etc. but not good for high performance apps like games.
  • It is new so many libraries are still to be added, so it can help in building small applications but the developer can get stuck in between if they build large apps and want to go deeper in the framework.
  • Implementing some native features requires detailed knowledge of a platform.
  • Learning curve may be a concern if you are new to JavaScript and unaware of other cross-platform or hybrid frameworks like Cordova.