React Native — Intro
Tags: react, jsx, reactnative, expo
Published: 2018-05-10 19:10:50

---
title: React Native — Intro
published: true
tags: react,jsx,react-native,expo
canonical_url: https://medium.com/maestral-solutions/react-native-intro-5a9d87bb0813
cover_image: https://thepracticaldev.s3.amazonaws.com/i/21c9vy10zw40alyfgu3l.png
---


Following my previous [article](https://dev.to/nedimb86/starting-with-react-native-2edb), we are going to continue with an introduction to React Native. Assuming you have everything set up and ready, and you have created your first project and have seen “Hello world!” on the screen, what’s next?  
Well… We have been instructed to open **App.js** and make our modifications. So, let’s look into the project folder.

![](https://cdn-images-1.medium.com/max/538/1*5taeffaDQ4KwCq98Tf1g2g.png)

![](https://cdn-images-1.medium.com/max/304/1*aC-F0fHpOv5qTmZ5L0L-8Q.png)<figcaption>Project folder structure and initial screen — created using create-react-native-app</figcaption>

Before we continue I would like to mention that for this lesson I am using **create-react-native-app**, therefore if you have created your project using **react-native-cli** or **ignite-cli,** project folder will differ from what I will be referring to.  
There it is. App.js. And as much as it is tempting to open it, let’s first see what we can learn from **README.md**.

If we want to keep our project up-to-date we will need to update our dependencies, which should be quite a simple task. But beware of [dependency compatibility](https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md). Create React Native App relies on 3 dependencies: **react-native, react** and **expo**, each being compatible with a narrow version of other two. Not to forget, the expo also needs to have specific **_SDK version_**, which can be set in the **_app.json_** file. Beside specifying SDK version, app.json can help us to name our app, give it an icon, version, specify supported platform, build details, [and set many other settings](https://docs.expo.io/versions/latest/guides/configuration.html).

Moving along we will see that we have 5 predefined scripts:

- npm start or yarn start used to run the app in development mode. If you need to clear cache run npm start --reset-cache flag.
- npm test used for running test. The project is set up to use **jest**, but you are free to change it to your likening. If you decide to continue with jest, all you need to do is to create files inside a _\_\_test\_\__ folder or with _.test_ extension, and your tests will be ready running.
- npm run ios used to run the project on iOS Simulator. The same can be achieved with npm start since one of the available options is to run the app on iOS Simulator as well.
- npm run android will run the app on Android device or emulator. Keep in mind that you will need a device connected or emulator started before running this script. As for the previous script, same goes for this one, the app can be run on Android with npm start as well.
- npm run eject if you find yourself that you need to add native code, do not worry, running this script will put you on the same track as if you have created your app with react-native-cli, but make sure that you have react-native-cli installed globally.

If you are unlucky one and everything does not run smoothly on the first try, there is a list of [**troubleshooting**](https://github.com/react-community/create-react-native-app/blob/master/react-native-scripts/template/README.md#troubleshooting) suggestions related to _networking, iOS Simulator not running, and QR Code not scanning_.

We have prolonged opening _App.js_ enough. So let’s check it out.

```
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
      </View>
    );
  }
}

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

#### What do we have here?

First of all, we can notice that code is written using **_ES6_**. I am assuming that we are all familiar with it to some degree. For those that want to learn more please check out [_this link_](https://babeljs.io/learn-es2015/).   
React Native comes with ES6 support so there is no need to worry about compatibility. To ensure you how it is much simpler to write the code using ES6, here is _a_ [_link_](https://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz=JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wG4AoUSWOAbzgGUYBPAGyQYAskkYAaOABUkAD35wAasCQB3OAF842XASLoYAWgB2KGMABuSMuXKjq8ACZJMKAK6t4aVigDOLuAEEwYOKJhItC3dkdQA6AGFcSC0A-FpyODgiQKQoAAoASjoExKTeWygtODSc3LgAHilZOBcWdgBeWlq2JBdQtAgtGBRgGKh5AD5SsorhMQGAeTAAuFsfLzBQgCt3GAga7poZaABrXoBzOE64ZggCuBRvAEJygHoxmCGR3PKHgfDOFC191pOzuBAKB2SDgMmArFYF1sa0BejQKAhzDyrAgKAsoTub2GZVefgGXCBINO5zAnE6ILWR2mRRg3DgVkMKOmUABAVsGPueOxFVuVRkT1yGQoiXk5FF5A6WlqGxa7nqjDqHG4vHaan8aXiiUl3V6qQAXNkyph2CIDQBGPjDABG6B2-xwtkCkRRUAN-AAxJgvfhLWUEcB9loAJL-EAuN1oWKpH3DJa2WrATDMSJdWIRqNQGMiy3yIVAA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=true&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=6.26.0&envVersion=) to our code after it is compiled.

Moving along we can see \<Text\>Lorem Ipsum\</Text\>, which might be unusual to some of us. This is **_JSX_** , _React_ feature for embedding _XML_ within _JavaScript_. Contrary to other framework languages that let you embed your code inside markup language _React_ lets us write markup language inside the code. This is one of the reasons why we have _React_ as one of our dependencies.

### React

As we have already seen we need to know of _React_ if we want to write _React Native_, but do not worry, if you do not know _React_ you will still be able to follow along. That being said, we will look into two types of data that control _React_ component and two different types of components.

```
import React, { Component } from 'react';
import { Text, View } from 'react-native';

const Greeting = ({name}) => <Text>Hello {name}!</Text>;

export default class GreetPeople extends Component {
    constructor(props) {
        super(props);
        this.state = {
            doeName: 'Doe'
        };
    }
    render() {
        const janesName = 'Jane';
        return (
            <View style={{marginTop:40, marginLeft:20}}>
                <Greeting name='John' />
                <Greeting name={janesName} />
                <Greeting name={this.state.doeName} />
            </View>
        );
    }
}
```

The code above is all we need, so let’s break it down.

#### Functional Components

Also known as presentational or stateless components. They are dump components that should not contain any complex logic and should be used for displaying a specific part of context or as wrappers to apply specific styles.

```
const Greeting = (props) => {
return (
 <Text>Hello {props.name}!</Text>
 )
};

----- or after shortening the code -----

const Greeting = ({name}) => <Text>Hello {name}!</Text>;
```

#### Class Components

More complex components that should deal with all necessary logic for displaying the content. _React_ has something called _component lifecycle_ and those should be handled inside class components. One of the _lifecycle_ examples is the _constructor_. Some of the others are _componentDidMount, componentWillUnmonut,_ and others. We will cover them as we need them.

```
export default class GreetPeople extends Component {
    constructor(props) {
        super(props);
        this.state = {
            doeName: 'Doe'
        };
    }
render() {
        const janesName = 'Jane';
        return (
            <View style={{marginTop:40, marginLeft:20}}>
                <Greeting name='John' />
                <Greeting name={janesName} />
                <Greeting name={this.state.doeName} />
            </View>
        );
    }
}
```

I would like to note that we do not need to have the constructor in every class component.

#### Props

Props are used for customizing the components. In our case, \<Greeting /\> component has a prop name, and as we have seen we can pass it a string directly or we can pass it a constantan inside curly braces.

```
const janesName = 'Jane';
    return (
        <View style={{marginTop:40, marginLeft:20}}>
            <Greeting name='John' />
            <Greeting name={janesName} />
        </View>
    );
```

If we are passing prop, let say fullName, to a class component we will access it with _this.props.fullName_, while in a functional component we will use _props.fullName_ (we will omit _this_ keyword).

#### State

While _props_ are passed from parent to child, the _state_ is what we are going to use with the component itself. We can initialize the _state_ in the _constructor_, but if we want to change it we should use this.setState() function. It accepts two parameters, object that will update the state, and a callback function that will execute once the state is updated. We should not worry about re-rendering the component since it will re-render every time the state or the props for the component have been changed.

```
constructor(props) {
    super(props);
    this.state = {
        doeName: 'Doe'
    };
}

componentDidMount(){
    setTimeout(
        () => this.setState({doeName:'Alex'}),
        3000
    )
}
```

Ok! I think we had enough of _React_ for now. Let’s go back to _React Native_.

### Styling

Well, sooner or later we will get bored at looking at same style over and over. So, what can we do about it? It’s easy. We will create CSS file, add our style, and… NO! _React Native_ does not play that way. But not to worry. Styling _React Native_ is not at all more complex. We will write our styles using JavaScript.

All of the core components accept prop named _style_ which accepts an object that contains our styling, that we write similar to CSS. The difference is that instead of dashes we are using camel casing (instead of font-family we will have fontFamily) and that our values unless they are only numeric, need to be surrounded by quotations (color: blue is color: 'blue'). With further ado, let’s look how we style _React Native_ component.

```
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class LotsOfStyles extends Component {
    render() {
        return (
            <View style={{margin:40}}>
                <Text style={styles.red}>just red</Text>
                <Text style={styles.bigblue}>just bigblue</Text>
                <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
                <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
                <Text style={{color:'yellow'}}>yellow</Text>
                <Text style={[styles.bigblue, {color:'green'}]}>bigblue, then green</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    bigblue: {
        color: 'blue',
        fontWeight: 'bold',
        fontSize: 30,
    },
    red: {
        color: 'red',
    },
});
```

As we have seen we can have two different approaches, somewhat similar to the inline style and class-based style. Also lets notice that we can easily combine styles by passing an array of objects to _style_ prop instead of an object.

### Dimensions

It should not be strange to us that we can use height and width to determine component size on the screen. Also, we can assume that our dimension can be fixed and flexible. So, how we are setting each in _React Native._

As for fixed, it is as simple as setting height and width. The trick is that all dimension in _React Native_ are **unitless** and represent **density-independent pixels**.

```
import React, { Component } from 'react';
import { View } from 'react-native';

export default class FlexDimensionsBasics extends Component {
    render() {
        return (
            <View style={{flex: 1}}>
                <View style={{flex: 3, backgroundColor: 'powderblue'}} >
                    <View style={{width: 50, height: 50, backgroundColor: 'orange'}} />
                    <View style={{width: '50%', height: 50, backgroundColor: 'green'}} />
                    <View style={{width: 150, height: 50, backgroundColor: 'red'}} />
                </View>
                <View style={{flex: 2, backgroundColor: 'skyblue'}} />
                <View style={{flex: 1, backgroundColor: 'steelblue'}} />
            </View>
        );
    }
}
```

Lets now check out flexible dimensions. This can be achieved with _flex_ property.

> [**A component can only expand to fill available space if its parent has dimensions greater than 0. If a parent does not have either a fixed**](https://facebook.github.io/react-native/docs/height-and-width.html)[**width and**](https://facebook.github.io/react-native/docs/height-and-width.html)[**height or**](https://facebook.github.io/react-native/docs/height-and-width.html)[**flex, the parent will have dimensions of 0 and the**](https://facebook.github.io/react-native/docs/height-and-width.html)[**flex children will not be visible.**](https://facebook.github.io/react-native/docs/height-and-width.html)

While talking about flex, we need to say that we can use flexbox principles to layout our components. And something that we need to keep in mind is that flexbox in React Naive slightly differs from what we are used on the web.

> [**Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with**](https://facebook.github.io/react-native/docs/flexbox.html)[**flexDirection defaulting to**](https://facebook.github.io/react-native/docs/flexbox.html)[**column instead of**](https://facebook.github.io/react-native/docs/flexbox.html)[**row, and the**](https://facebook.github.io/react-native/docs/flexbox.html)[**flex parameter only supporting a single number.**](https://facebook.github.io/react-native/docs/flexbox.html)

### Components

Now we know how to apply a basic style to our app. Where to next? Well… we will need something to style. And that something is _React Native_ components. So let’s have a look into few.

**View** : the most fundamental component for building UI — as div for web  
**Text:** used for displaying text — heading, and paragraphs for web  
**TextInput:** used for inputting text into the app via keyboard — input for web  
**StyleSheet:** creates styles — acts style tag for web  
**Image:** used for displaying images — same as img on web  
**Button:** gives us buttons — acts like button for web  
**Platform:** helps us to determine either we are running our code on Android or iOS  
**Alert / AlertIOS:** the name says it — as JavaScript alert message  
**ScrollView:** helps us to scroll the content that is higher or wider than our device  
**FlatList:** displays similarly structured data; unlike ScrollView it renders only visible items  
**Touchable “components”:** creates touchable views — similar to anchor tags on web

Let’s not go overboard with listing components. Those are some basic ones that we will be using the most. As for other, we will mention them as appropriate to our case.

We have already seen how we can style _Text_ and _View_ in our examples. Styling others is not much different. For the full list of styling attributes, you can check the official documentation.

### Conclusion

I think we have covered enough in this article. We now know how to create a project using _create-react-native-app_ and we have a basic understanding of what we get out of the box when doing so. We have learned just enough React to be able to write code for our app. And we have shown how to style React Native component, as well as how to give it dimensions. In addition to that, we have mentioned fundamental React Native components to have us up and ready when we want to build a simple app.

The code used here can be found on my GitHub repository:

[nedimb86/MyReactNativeApp](https://github.com/nedimb86/MyReactNativeApp)

* * *