Subscribe now

Our First App [11.17.2016]

Remember the application we created in the last episode? We will make sure we understood all of it, and we are going to make some changes and add some components.

It's worth mentioning that React Native is a framework to build mobile apps. There are a lot of types of mobile applications like games, simple and complex apps. If you are building your app, you will need to organize your app some way, for example in layers, depending on the architecture you are using. In the Mobile world, there are a lot of architectural patterns, like MVVM or even MVC. You need to have in mind this when you start building your app.

We are going to build a simple app just to determine if a person is tall or not. We are going to have a model called Person which represents our data. Let's use the same code that we started with in 001.3 as a starting point

class Person {
  constructor(name, height) {
    this.name = name;
    this.height = height;
  }

  isTall(){
    return this.height > 200 ? "is tall" : "is not tall" ;
  }
}

export default Person;

Everything in the Person class should be related to Person, but we have some logic that's unrelated to that a bit: the method isTall. We may have something like new PersonDecorator(person), this is generally what we call a decorator pattern and it's kind of nice to separate the parts that are just concerned with view logic from those that are related to the data and objects in the application. However, we might also choose to just put this function directly into our component as a private method until we find we need it somewhere else.

We won't do that yet, but I wanted to bring it up. Now let's build out the application. Here we'll just edit index.ios.js as we're working on an iOS app, but you can feel free to do the same to index.android.js if you're not on a Mac or if you are focused on Android.

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Person from './models/Person'

class MyFirstProject extends Component {
  render() {
    let person = new Person("Josh", 209);

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          {person.name} {person.isTall()}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

AppRegistry.registerComponent('MyFirstProject', () => MyFirstProject);

Remembering, we can also put the function isTall() into our component, but we won't do this right now.

With this, you should have on your screen something like: Josh is tall. We've now made our first custom React Native app. See you soon!

Resources