Skip to content
  • Services
  • About
  • Partners
  • Work
  • Insights
  • Careers
  • Contact
  • Services
  • About
  • Partners
  • Work
  • Insights
  • Careers
  • Contact
September 22, 2015

Aligning Children using Flexbox in React Native

Community and Events, Front End Development, React

This tutorial is part of a series, in which we are learning all about the layout system in React Native. I recommend that you read the previous tutorial about how flexDirection works as we will continue using the same project that we created in the first tutorial.

Now that we have a better understanding of flex direction, let’s review the alignment options that we have available. We will create a container that displays a message with a title, we will learn how to align this component.

First we need to create the required views and texts, open the index.ios.js tab in your favorite text editor and add the following code to the render method, as a child of the content view.

   
'use strict';
  
var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Component
} = React;
 
class ReactLayouts extends Component{
    render() {
        return (
            <View style={styles.mainContainer}>
               <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 style={styles.content}>
  
                    {/* START NEW CODE */}
 
                    <View style={styles.messageBox}>
                        <View>
                            <Text style={styles.messageBoxTitleText}>A simple mesage</Text>
                        </View>
                        <View>
                            <Text style={styles.messageBoxBodyText}>This is just a dummy sample it will help us to see the alignment in action.</Text>
                        </View>
                    </View>

              {/* END NEW CODE */}
  
                </View>
            </View>
        );
    }
}

In the previous code we’ve defined a message box container. It’s important to notice that we are adding just the code between the comments, the toolbar code was defined before in the flexDirection tutorial. We only have the title, and the content is completely static.

iOS Simulator with Title and Static Content

Once we have the component rendered, we need to add some styles to the stylesheet object.

   
var styles = StyleSheet.create({

  
   // …

    messageBox:{
        backgroundColor:'#ef553a',
        width:300,
        paddingTop:10,
        paddingBottom:20,
        paddingLeft:20,
        paddingRight:20, 
        borderRadius:10
    },
    messageBoxTitleText:{
        fontWeight:'bold',
        color:'#fff',
        textAlign:'center',
        fontSize:20,
        marginBottom:10
    },
    messageBoxBodyText:{
        color:'#fff',
        fontSize:16
    }
});

These is a pretty common styles, just some colors, paddings, fonts and so on. As a result we should have something as in the following image.

iOS Simulator with Simple Message Pop up

Now that we have a component, we can start playing around with the alignment. Aligning components in React is very straightforward, all we need to do is define the alignItems property in the container’s styles.

   
var styles = StyleSheet.create({
    //..
    content:{
        backgroundColor:'#ebeef0',
        flex:1,
        alignItems:'center'     //<-----
    },
  
    //...
});

This will automatically center the component on the screen. Because we didn’t define a flex direction, the column direction is used. Therefore the component is horizontally centered.

On the other hand, if we set the flex direction to row, the component will be vertically centered. This is a very important concept to keep in mind.

2 images of the iOS Simulator with a Simple Message Horizontally Defined with flexDirection set to column

We have three more options to align our component.

1.flex-start which will align the component at the top/start of the parent component.

2.flex-end which will align the component to the bottom/end of the parent container.

3.stretch will set the height or width to 100% of the container, based on the flex direction.

We can also justify our components. For example if we want to center our components horizontally and vertically, we will need to apply the following changes to our styles.

   
var styles = StyleSheet.create({
    content:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
   …
});

First we set the flex direction to row, this will arrange the children horizontally. In order to center the component horizontally we use the alignItems property, then we use justifyContent to vertically center the component.

iOS Simulator with a Simple Message centered horizontally and with justifyContent

We have a few more options to justify our component to the left, right, as well as to add space between or around the children.

Conclusion

The layout system in React Native is very powerful and flexible, we can create any layout with all the available options that we have. Understanding how flexbox works is important in order to build our very custom layouts and components.

You can download the code from Github. I recommend you to take a look at the documentation and try all the possible values in the available properties.

Posted in Community and Events, Front End Development, React
Share this

Crysfel Villa

Crysfel Villa was 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 co-authored The React Native book, which was published in December 2016.
Follow

Related Posts

  • React Navigation and Redux in React Native Applications
    React Navigation and Redux in React Native Applications

    In React Native, the question of “how am I going to navigate from one screen…

  • React Navigation and Redux in React Native Applications
    React Navigation and Redux in React Native Applications

    In React Native, the question of “how am I going to navigate from one screen…

Subscribe to the Modus Newsletter

Receive the latest blog articles and insights every month from the Modus team.

Let's Chat

If forms aren’t your thing, you can always call us (+1-855-721-7223).

Modus-Logo-Primary-White.svg
  • Services
  • About
    • Newsroom
  • Partners
  • Work
  • Insights
    • Blog
    • Modus Labs
  • Careers
Virginia (US)

12100 Sunset Hills Road
Suite 150
Reston, Virginia, 20190
Tel: +1-855-721-7223

California (US)
12130 Millennium Dr

Los Angeles, CA 90094

Missouri (US)
609 E High St

Jefferson City, MO 65101

Romania

Str. Mihai Veliciu, no. 17
Cluj-Napoca, Romania
Tel: +40-0786-887-444

Costa Rica

2nd Floor, Plaza Koros, Av 3
San José, Santa Ana, Costa Rica

© 2021 Modus. All Rights Reserved.

Privacy Policy | Accessibility Statement | Sitemap

This website uses cookies.
These cookies are used to collect information about how you interact with our website and allow us to remember you. We use this information in order to improve and customize your browsing experience, and for analytics and metrics about our visitors both on this website and other media. To find out more about the cookies we use, see our Privacy Policy.

Accept
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Scroll To Top