Getting Started with React

Published Sep 12, 2017


React goes mobile with React Native

In recent years, React (a JavaScript library built by some dope Facebook Engineers) has been the goto framework for cross platform development owing to its big selling point, React’s great Developer Experience/User Experience. Described by its creators as “A JavaScript library for building user interfaces”, React focuses on the view portion of your application. In more concrete terms, this means that when writing a React Native app, your view code will consist of writing React components, which are small pieces of code that describe how a portion of your app should look based on some set of input data. Let’s look at a small example component which can be used to display a simple button. (styles will be omitted for clarity sake.)

const Button = React.createClass({
propTypes: {
onPress: React.PropTypes.func.isRequired,
text: React.PropTypes.string.isRequired,
},
render() {
return (
<TouchableOpacity onPress={this.props.onPress} style={...}>
<Text style={...}>{this.props.text}</Text>
</TouchableOpacity>
);
}
});

This button component has two pieces of input data: onPress , a callback function for handling an event of when the button is pressed; and text, which is the string that gets displayed inside the button. The XML-like structure that is returned by the render function is called JSX, the syntactic sugar for function calls in React. And TouchableOpacity and Text are just existing components that are included with React Native. Now that the Button component has been created, it can be used many times throughout the application, with consistent behavior and styling.

This simple example demonstrates how React Native apps are built, bit by bit and component by component; you can create components that represent increasing layers of abstraction which later turn into a large code base. For example, you might create a ButtonGroup component that contains several connected buttons. And building on top of that, you can write components that represent entire screens. Even as your app gets larger, components remain understandable and manageably sized at each level.

What A Really Native Framework

If you have written apps using Android Studio, you’ll immediately recognize many of React Native’s components. React Native’s components are just more like the classes in your Java codes for handling XML event. React’s top feature, simplify building rich User Interfaces, when it launched initially for the web was making your app’s view layer a pure output of state. As a developer, this means that instead of making changes to view components (for example, programmatically altering the text or color of a button by calling a function on it), what you simply do is define what your view should look like based on input data, and React intelligently makes the changes for you when the state changes -Awesome, right?

React Native component definitions behave pretty much just like React for web components, but target native UI widgets instead of HTML. So instead of using a <div>, you would use a <View> (which on iOS gets rendered to a native UIView, and on Android, android.view). When your components’ data changes, React Native will calculate what in your view needs to be altered, and make the needed calls to whatever native UI widgets are displayed. And amazingly, JavaScript and React Native are more than capable of keeping your app running at 60 frames per second.

P.S : React Native helps developers to build awesome native apps their customers will love, without any increase in budget building two separate apps could entail.

Loving The Framework? Let’s Get Set Up With React

React Native uses Node.js, a JavaScript runtime, to build your JavaScript code. If you don’t already have Node.js installed, it’s time to get it!

For Mac, Install Homebrew using the instructions on the Homebrew website, then install Node.js by executing the following in a Terminal window:

brew install node

And for Windows, install chocolatey using the instructions on the Chocolateywebsite as well, then install Node using the command:

choco install nodejs.install

Next, use homebrew to install watchman, a file watcher from Facebook:

brew install watchman

This is used by React Native to figure out when your code changes and rebuild accordingly. It’s like having Xcode (on MacOS)do a build each time you save your file.

Next use npm to install the React Native Command Line Interface (CLI) tool:

npm install -g react-native-cli

This uses the Node Package Manager (npm) to fetch the CLI tool and install it globally, so does Yarn

Or Yarn:

yarn global add react-native-cli

Navigate to the folder where you would like to develop your React Native application, and use the CLI tool to construct the project:

react-native init AppName

This creates a starter-project containing everything you need to build and run a React Native application. If you look at the created folders and files you will find a node_modules folder, which contains the React Native framework. You will also find an index.android.js file, which is the skeletal app created by the CLI tool. There is also an android folder, containing an Android Studio project and the small amount of code required to ‘bootstrap’ your application. Finally, there are its iOS counterparts. While in your project folder, run react-native run-ios (iOS) or react-native run-android (For Android) to build your React Native project; better still run the command:yarn start (for Yarn users) while npm users should run the npm start command.

After this, you should notice the React Native packager, running under node. Below is snippet of the running React Native Packager. You’ll find out what it does shortly.

┌──────────────────────────────────────────────┐
│ Running packager on port 8081. │
│ │
│ Keep this packager running while developing on any JS projects. │
│ Feel free to close this tab and run your own packager instance if │
│ you prefer. │
│ │
│ https://github.com/facebook/react-native │
│ │
└──────────────────────────────────────────────┘
Looking for JS files in
/Users/bashirk/Desktop/React/AppName
[6:15:40 PM] <START> Building Dependency Graph
[6:15:40 PM] <START> Crawling File System
[6:15:40 PM] <START> Loading bundles layout
[6:15:40 PM] <END> Loading bundles layout (0ms)
[Hot Module Replacement] Server listening on /hot
React packager ready.
[6:15:41 PM] <END> Crawling File System (747ms)
[6:15:41 PM] <START> Building in-memory fs for JavaScript
[6:15:42 PM] <END> Building in-memory fs for JavaScript (653ms)
[6:15:42 PM] <START> Building in-memory fs for Assets
[6:15:42 PM] <END> Building in-memory fs for Assets (277ms)
[6:15:42 PM] <START> Building Haste Map
[6:15:42 PM] <START> Building (deprecated) Asset Map
[6:15:42 PM] <END> Building (deprecated) Asset Map (49ms)
[6:15:42 PM] <END> Building Haste Map (400ms)
[6:15:42 PM] <END> Building Dependency Graph (2094ms)

Say Hello To React Native

Before getting started on building your world class application, we are going to build a very simple Hello World app to test your React environment. With this, you’ll be introduced to the various components and concepts as you go along.

Firstly, open index.android.js in a text editor of choice and delete the current contents since you’re going to build your own app from scratch. Add the following to the start of the file:

'use strict';

This enables Strict Mode , which adds improved error handling and disables some less-than-ideal JavaScript language features.

Next, add the following lines:

var React = require('react');
var ReactNative = require('react-native');

This loads the react & react-native modules and assigns them to variables called React & ReactNative. React Native uses the same module loading technology as Node.js with the require function, which is roughly equivalent to linking and importing libraries in Swift or Android Studio.

Below the require statement, add the following:

var styles = ReactNative.StyleSheet.create({
text: {
color: 'black',
backgroundColor: 'white',
fontSize: 30,
margin: 80
}
});

This defines a single style that you will shortly apply to your “Hello World” text. If you’ve done any web development before, you’ll probably recognize those property names. The React Native StyleSheet class used to style the application UI is similar to the Cascading Style Sheets (CSS) used on the Web.

Now for the app itself! Still working in the same file, add the following code just beneath the style declaration above:

class MyClass extends React.Component {
render() {
return React.createElement(ReactNative.Text, {style: styles.text}, "Hello World!");
}
}

That’s a JavaScript class!

MyClass extends React.Component , the basic building block of the React UI. Components contain immutable properties, mutable state variables and expose a method for rendering. Your current application is quite simple and only requires a render method.

React Native components are not UIKit classes; instead they are a lightweight equivalent. The framework takes care of transforming the tree of React components into the required native UI.

Finally, add the following to the end of the file:

ReactNative.AppRegistry.registerComponent('MyClassNo', function() { return MyClass });

AppRegistry defines the entry point to the application and provides the root component.

Save your changes to index.android.js and then return to Android Studio. Ensure the AppName scheme is selected with one of the Android simulators, and then build and run your project. After a few seconds you’ll see your “Hello World” app in action:


Welcome to the awesome world of React Native!

React’s Great Developer Experience

Highly productive developers are happy developers. While developing on some development environment like Android Studio, you repeatedly have to wait for your app to compile and restart while making any edits; but with React, any changes to a codebase in React Native are made to your running app without the need to restart the app.

React Native uses flexbox for creating app layouts. While every layout engine has its own learning curve, ups and downs, React Native’s support for flexbox means you can directly use the exact same layout code for Android, iOS and web, instead of learning three different engines.

Conclusion

Between the ease of development, quality of the apps built with React, and the richness of the platform and ecosystem, You will be having a lot of fun learning and building with React Native. And in any case you wish to learn more, head over to the official React Native page! Happy coding!

Discover and read more posts from Bashir Korede
get started
Enjoy this post?

Leave a like and comment for Bashir

1
Be the first to share your opinion

Get curated posts in your inbox

Read more posts to become a better developer