React Native Layout System


July 21, 2015
ReactNativelogo

If you’ve been working with web technologies for a while, jumping into React Native is very straightforward, especially if you are familiar with ES6. Installing the development environment is relatively easy if you are familiar with NPM. Follow the instructions on the official website to get started.

The layout system is a fundamental concept that needs to be mastered in order to create great layouts and UIs. React Native uses Flexbox to create the layouts, which is great when we need to accommodate our components and views in different screen sizes or even different devices.

Let’s start by creating a new app. In order to do this, we need to run the following command in our terminal.

  
$ react-native init ReactLayouts

This  command will generate a new project with a very basic application scaffolding. Open ReactLayouts.xcodeproj in Xcode and run the app in a simulator. You should see something like the below image.

01-react-layouts

Now we are ready to start building our app.

Understanding column and row

When we use flexbox, we can arrange the children of a container in two directions, vertically or horizontally.

By default, all children will be arranged vertically. The flex direction is called column. If we want to arrange the children horizontally, we need to change the flex direction to row.

02-flex-direction

Let’s create a toolbar in the first tab. The toolbar will have one button on the right, one on the left, and a centered title. Add the following code to the index.ios.js file.

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Component
} = React;
  
class ReactLayouts extends Component{
    render() {
        return (
          <View>
                <View style={styles.toolbar}>
                    <Text style={styles.toolbarButton}>Add</Text>
                    <Text style={styles.toolbarTitle}>This is the title</Text>
                    <Text style={styles.toolbarButton}>Like</Text>
                </View>
            </View>
        );
    }
}
  
var styles = StyleSheet.create({

});
    
AppRegistry.registerComponent('ReactLayouts', () => ReactLayouts);

As you can see, inside of the render method we have a container with a style called toolbar. Inside of this container we have three different text containers. If we refresh our application, we will see that all three texts will be displayed vertically, one after another. However, we need to display the text horizontally. The title text should be flexible, depending on the device width.

In order to arrange the direction of the text horizontally, we need to change the flexDirection property of the toolbar container.

  
var styles = StyleSheet.create({
    toolbar:{
        backgroundColor:'#81c04d',
        paddingTop:30,
        paddingBottom:10,
        flexDirection:'row'    //Step 1
    },
    toolbarButton:{
        width: 50,            //Step 2
        color:'#fff',
        textAlign:'center'
    },
    toolbarTitle:{
        color:'#fff',
        textAlign:'center',
        fontWeight:'bold',
        flex:1                //Step 3
    }
});
  1. Change the flex direction to the parent. In this case, the row direction will display the children horizontally.

  2. Set the width of the buttons. This step is not necessary, but if we don’t set a fixed width, then the default width of the text will be used.

  3. Set the title to flexible. This means that this container will use all the available space. This is really neat when changing from portrait to landscape because the toolbar will expand horizontally based on the available space.

Here’s the result of our new toolbar.

03-flex-row-toolbar

Go ahead and change the simulator to landscape using Command + Right/Left arrow key (⌘+Left Arrow), you will see how the title will adjust its width in order to use all the available space.

Now let’s add some content after the toolbar. We need to add a container, and expand it to take all the available vertical space. In order to add a new container, let’s modify the render method.

  
render() {
    return (
        <View style={styles.mainContainer}>     //Step 1
            <View style={styles.toolbar}>
                ...
            </View>
            <View style={styles.content}>            //Step 2
                <Text>This is the content</Text>
            </View>
        </View>
    );
}
  1. Add a new style definition to the main container. We need to expand this container to take up the full screen.

  2. Define the new content. In this case, a view with text.

Now let’s style the two new elements.

  
var styles = StyleSheet.create({
    ...
  
    mainContainer:{
        flex:1                  //Step 1
    },
    content:{
        backgroundColor:'#ebeef0',
        flex:1                //Step 2
    }
});
  1. Make the main container flexible. This way, the component will take all the available height. This is handy when changing from portrait to landscape.

  2. Define the content as flexible. We also set a background color so we can see how the container takes the available space.

04-flex-row-toolbar-2

In the left image, the content is not flexible, therefore the height depends on the content itself. In the right image, the content is flexible, the height will be adjusted to use all the available vertical space. As you can see, it’s very easy to make flexible containers in React Native.

Conclusion

To recap, whenever we need to arrange the children of a container horizontally, we need to set the flex direction to row. By default, the flex direction is column. This means that the children will be arranged vertically.

We can use these concepts to create responsive layouts. The width or height of a container will use all the space in the device. Our next tutorial in the series will show you how to align the children of a container.


Villa_Crysfel
Crysfel Villa is a Sr. Engineer at Modus Create. He's a passionate JavaScript coder and an accomplished software developer with over 8 years of experience on technical training, consulting and systems analysis. When he's away from the keyboard, he enjoys playing the guitar, piano and violin. Crysfel currently lives in NY and can be found attending tech meetups throughout the city. He has a React Native book due for release in December 2016.

  • Navjeet Chabbewal

    All the images seem to be missing on this post ?

    • ModusJesus

      Thanks Navjeet! We’ve found an issue in our posting process and will resolve it. Many thanks for taking the time to give us as heads up

  • http://peterlazar1993.github.io/ Peter Lazar

    Thanks for the quick intro :)

  • randy

    question about this. The toolbar I’ve made so far looks great, however, I noticed that when I replace a text with a touchablehighlight, the touchable highlight’s clickable area does not include the top and bottom padding. I tried adding top and bottom padding, but that only expanded the height of the toolbar. I also tried making the toolbar into a flexdirection: row, so that its children could be centered vertically, but that did not work. Any idea on what could be done? Just want to expand the clickable region of my touchableHighlight without fudging with the toolbar. Thanks! Great tutorial!

  • Santino Wang

    Why toolbar is covering the status bar(Carrier, 10:28AM, battery icon)??

  • http://www.mandricore.com Kristian Mandrup

    I had big problems displaying a TextInput initially. For some reason, it kept being completely squashed into nothing. I had assumed it would have some default width or height if it had a value or placeholder, but no…
    Would be nice if you could include positioning a TextInput with a Send button horizontally as part of the tutorial :)

  • Kenichi Shibata

    You rock Crysfel!!!!!

  • Alexis Duran

    Awesome dude thanks!

  • Charles Dostoevsky

    this is great, thank you!

  • http://pieterlelaona.com/ piter lelaona

    Thanks.. This is great. You Rock Man!!!!

  • Shahriza Khairudin

    thank you for the writing! it helps.


What We Do

We’ll work closely with your team to instill Lean practices for ideation, strategy, design and delivery — practices that are adaptable to every part of your business.

See what Modus can do for you.

LET'S GET STARTED

We're Hiring!

Join our awesome team of dedicated engineers.

Loading...

APPLY NOW