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

Sound Browser: Grand Prize Winner of the Capitol360 Hackathon

Music videos, which comprise an important part of the video-streaming industry, are consistently the most-viewed content on streaming giants, such as YouTube and Vimeo. In exchange for free viewing, those channels serve advertisements for revenue. That business model creates a clumsy user experience, however, as a result of often-repeated ads that don't relate to the content.

Read more
Building a Live Feed of FIFA World Cup Moments

Widely acclaimed as the world’s biggest sporting event, the World Cup has established itself as the most captivating tournament to look forward to across the globe. Dating back to 1930, when the first World Cup was hosted in Uruguay, it has always engendered numerous moments of excitement, not only for the participating teams but also for the countries they ably represented. Little could anyone have anticipated that a game of 22 able-bodied men running to take possession of a leather ball could become so famous.

Read more
Auto AI Content Recognition Tagging in Cloudinary DAM

Automating the categorization of your images and videos can help democratize access to your organization's creative assets. Many teams throughout your organization have likely spent a lot of time and effort generating high-quality content, but it'd be all for naught if the content just ends up in some anonymous folder on somebody's hard drive or is randomly dropped into your cloud storage with no functional organizational strategy.

Read more
Capitol 360 Incubating New Waves of MusicTech

Last month, we had the pleasure of supporting Capitol Music Group’s first ever hackathon, the first in a series of hackathons as part of its newly launched Capitol360 Innovation Center, established to bridge the gaps between music and tech and make music better for everyone. We are proud to be a founding technology partner and were honored to play a part in Capitol’s first-ever 24-hour hack. And because so many of us are avid and longtime music fans we’re also personally thrilled to have the opportunity to work with one of the most influential leaders in music to foster these new and meaningful connections.

Read more
Headshot transformations from Fluent + Velocity 2018

On June 13-14, O'Reilly held its annual Fluent + Velocity conference in San Jose and it was great! Cloudinary set up a pretty incredible booth and brought in a professional photographer to take headshots of the attendees who stopped by. Once a photo was snapped, the raw camera file was immediately uploaded to our media library and transformed into something that can be posted right away on LinkedIn.

Read more