Sunday, May 14, 2017

Dynamically Creating Your UI using React Native

When building mobile applications, you often need to dynamically create your UI. For example, you are creating a generic conference app and you need to load the tab bar items based on the number of days a conference has. In this case, you need to create the UI at runtime, rather than design time. So how do you do it in React Native? This post shows how it can be done.

Here I have an array simulating a list of sessions for each day:


var sessions = ['iOS', 'Android', 'Windows Phone', 'Tizen']

In the real world you probably will load this from a configuration file or from the Web.

Next, we will add tab bar items to our UI based on the sessions array:

  render() {
    return (
      
          
         {sessions.map((session, i) =>
           
             style={[styles.tabBarButton, this.getStyle({i}) ]} >
             {session}
           
         )}          
        
      
    );
  }

You can use the map() function to iterate through each item in the sessions array, and then add each tab bar buttons to the UI. The getStyle() function allows you to apply unique style for each tab bar item and is defined as follows:

  getStyle(index) { 
     //---index is a dictionary, e.g { i : 1 }         
     switch (index['i']) {

       //---return predefined styles
       case 0: return styles.button1;    
       case 1: return styles.button2;      
       case 2: return styles.button3;      
       
       //---return dynamic style
       case 3: return {backgroundColor: '#FCBF2E'};  
       case 4: return {backgroundColor: '#FC9626'};              
       default: return {backgroundColor: '#FCBF2E'};              
     }
  }

Here, I am demonstrating that the function can return either a predefined style, or you can dynamically create the style if you so desire. 

The styles used by my example are as follows:

     tabBar: {
    flexDirection:'row',   
    height: 50
  },
  tabBarButton: {
    flex: 1,   
    alignItems:'center',
    justifyContent:'center'
  },
  tabBarButtonText:{   
    fontWeight:'bold'   
  },
  button1: { backgroundColor: '#8BC051' },
  button2: { backgroundColor: '#CCD948' },

  button3: { backgroundColor: '#FDE84D' },

The figure below shows the UI with 4 tab bar items and 3 tab bar items (just remove the last item in the sessions variable).

No comments: