Cloudinary Blog

Getting Started with React Native: Part 1

Getting Started With React Native

What is React Native?

React Native is a popular open source software that enables you build mobile applications easily with JavaScript. Other similar and popular options out there include Ionic, Lungo, Sencha Touch and NativeScript Vue. You can use your existing knowledge of HTML5, CSS and JavaScript to develop mobile applications without having to learn a different set of skills.

What you need to know about React Native

To build mobile applications and be comfortable with React native development, you need to be armed with the knowledge of the following languages:

  1. HTML5
  2. CSS
  3. JavaScript
  4. React

Modern knowledge of JavaScript (ES6) is required. Wes Bos has a very good course on ES6. However, you can start with this quick tutorial that will provide you with enough knowledge to use React Native without frustration. If you know React, you possess 70 percent of the knowledge required to help you build mobile applications with React Native.

React Native Install Process

Building React Native mobile applications require you to have some software installed on your development machine that will provide the right environment to run and compile JavaScript code to native. React Native enables you to build iOS and Android apps with virtually the same code base.

Installation can be a herculean task. Be calm, be patient and follow the official guide to install everything you need to get started. Windows users can follow this very detailed guide from the folks at Infinite Red.

What You Need to Internalize

I’m sure you are wondering what this section is about. Thinking in React basically means thinking about your UI in terms of components when designing a web application.

While learning to build mobile applications with React Native, the sooner you internalize the React Native equivalents of basic HTML tags, the faster you can churn out mobile apps with your React knowledge.

Another thing you need to be aware of is that styling is different. T Styling your components in React Native via the StyleSheet module or inline styling is done like so:

  • <View> ⇔ <div>
  • <Text> ⇔ <p>, <h1-6>, <span>
  • <Image> ⇔ <img/>
  • <TextInput> ⇔ <input type=”text”/>
  • <Picker> ⇔ <select>
  • <Button> ⇔ <button>
<Text style={{color: 'red'}}> I love React Native</Text>
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

render() {
  return (
      <View style={styles.container}>
          <Text>Start building mobile applications today</Text>
      </View>
...

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Baby Steps: The Counter App

No, we are not starting with a “Hello World” app. We’ll build a simple counter app with React and convert it into a React Native App. This approach encourages you to simply use your existing React knowledge to build a React Native app without any hassle. Let’s get started.

Set Up

Install the create-react-app node module. This tool helps us to scaffold a React web app out of the box in less than a minute.

 npm install -g create-react-app

Now, run the create-react-app command via the command line:

create-react-app counter
cd counter

Create a components folder inside the src directory. This folder will house our Counter component.

Create the Counter Component

import React, { Component } from 'react';

class Counter extends Component {

  state = {
    count: 52
  }

  render() {
    const { count } = this.state;
    return (
      <section className="counter">
        <h1> Count: { count } </h1>
        <button className="full-width"> Increment </button>
        <button className="full-width"> Decrement </button>
        <button className="full-width"> Reset </button>
      </section>
    );
  }
}

export default Counter;

Counter

The buttons are currently inactive. Let’s add functionality to be able to manipulate the state. Add the handleIncrement, handleDecrement, and reset method.

  ...  
  handleIncrement = () => {
    this.setState({
      count: this.state.count + 1
    });
  }

  handleDecrement = () => {
    this.setState({
      count: this.state.count - 1
    });
  }

  reset = () => {
    // you can also pass in a function to setState
    this.setState({
      count: 52
    });
  }

We are almost done with the component. Now, make the button active by assigning the appropriate function to the onClick prop of the button.

...
render() {
    const { count } = this.state;
    return (
      <section className="counter">
        <h1> Count: { count } </h1>
        <button onClick={this.handleIncrement} className="full-width"> Increment </button>
        <button onClick={this.handleDecrement} className="full-width"> Decrement </button>
        <button onClick={this.reset} className="full-width"> Reset </button>
      </section>
    );
  }

Call the Counter Component in App.js

import React, { Component } from 'react';
import Counter from './components/Counter';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Counter />
      </div>
    );
  }
}

export default App;

Now, test your app again. It should work properly as shown below.

Counter

Convert React Counter App to React Native App

There are a couple of steps we must take:

  1. Import the required native components from React Native. Create a Counter.js file in the app root directory and import the required native components from React Native.

    import React, { Component } from 'react';
    import { StyleSheet, Text, View, Button } from 'react-native';
  2. Add the class methods, and replace some components in render()

    ...
    class Counter extends Component {
    
     state = {
        count: 52
     }
    
     handleIncrement = () => {
        this.setState({
            count: this.state.count + 1
        });
     }
    
     handleDecrement = () => {
        this.setState({
          count: this.state.count - 1
        });
     }
    
     reset = () => {
        this.setState({
          count: 52
        });
     }
    
     render() {
        const { count } = this.state;
        return (
          <View className="counter">
             <Text> Count: { count } </Text>
            <Button onPress={this.handleIncrement} title="Increment" />
            <Button onPress={this.handleDecrement} title="Decrement" />
            <Button onPress={this.reset} title="Reset" />
          </View>
        );
      }
    }

    Check out the following changes:

    • <section> became <View>
    • <h1> became <Text>
    • <button> became <Button>
    • onClick became onPress
    • We added a title prop because the text displayed inside a button in React Native has to be the value of the button’s title property.
  3. Import counter component in App.js

    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    import Counter from './Counter';
    
    export default class App extends React.Component {
      render() {
        return (
          <View style={styles.container}>
            <Counter />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });

Run your app. npm run ios for iOS and npm run android for Android. The demo below is the React Native iOS app.

react native

This is not very pretty. The buttons don’t look like buttons. They look like text just hanging out in the middle of white space. Changing the button’s background color in React Native Android simply requires adding the color prop:

<Button onPress={this.reset} title="Reset" color="#9C27B0" />

However, in React Native iOS, the process is different. The color prop only changes the color of the text. The background color remains unchanged. Let’s use a better component called TouchableOpacity like so:

Counter.js

import { StyleSheet, Text, View, Button, Image, TouchableOpacity } from 'react-native';
. . .
<TouchableOpacity onPress={this.reset} style={styles.resetButton} >
    <Text style={styles.resetText}>Reset</Text> 
</TouchableOpacity>

Add the styling at the end of the Counter.js file like so:

const styles = StyleSheet.create({
  resetButton: {
    backgroundColor:'#4583c9',
    paddingTop:10,
    paddingBottom:10,
  },
  resetText:{
      color:'#fff',
      textAlign:'center',
      paddingLeft : 10,
      paddingRight : 10
  }
});

Your reset button should look like the button in the image below:

Reset Button

There are a lot of things you can accomplish with the TouchableOpacity API. Check the docs on different ways to style and change the button’s state.

Conclusion

This is an introduction to React Native. Developing React Native applications requires you to switch frequently between the React Native Android and iOS docs to figure out how components work and display on screen for both devices. Managing state and using props is the same with React. You also could use Redux or Apollo Client with GraphQL.

You will be building media rich mobile applications in no time!

Note
For the direct mobile path, Cloudinary offers Android and iOS SDK solutions.

In the next part of this tutorial, we’ll build an image viewer app with React Native for the Android and iOS platforms. Stay tuned!

Recent Blog Posts

ImageCon2018: Toward Excellence in Interactive Visual Media

On April 12, 2018, Cloudinary hosted its second annual ImageCon conference, which brought together more than 200 professionals from developers to architects to designers to executives. We had two main goals for this year’s ImageCon: shine a light on interactive media through presentations by leading industry experts and foster an open exchange of media-related best practices and ideas among the attendees.

Read more
How To Make a jQuery 360 Product Viewer

eCommerce is a dynamic business. Visitors are constantly checking sites for the best deals or their favorite products, adding to their wishlists and exploring product recommendations from friends and influencers. At the same time, online vendors rely on numerous techniques - such as optimizing page load time, using sharp product images and aggressively targeting ads - to draw in shoppers and convert clicks into cash.

Read more
How to Make Boomerang Video Effect With Cloudinary

When you see the term boomerang, what is the first thing that comes to mind?

A thrown tool made of wood that returns to its thrower? Another definition is reversal, logically portraying the aim of the tool itself. Based on this definition, the term boomerang videos” came into play to depict videos that loop back and forth.

Read more
Shortening the Development Cycle of Media-Related apps with Cloudinary

Currently, the Android platform boasts the highest demand for mobile solutions, as evidenced by Google’s announcement in 2017 that there were two billion monthly active Android devices, a number that is likely to increase in the years ahead. For app developers like you, now is the right time to build and release solutions for Android. you might have also noticed that a higher percentage of apps being developed nowadays are filled with visual media: images and videos.

Read more