Pages

Friday, 6 November 2015

React-Native DrawerLayoutAndroid - How to Open the Menu on Click of an Menu Icon

Recently had a chance to develop an app using the react native. On of my requirement for the app was a hamburgur menu. While the DrawerLayoutAndroid available does the job, to a great extend, had a requirement to open the menu on click of the Home Menu/Hamburgur menu.

This turned out to be quite a challenge. The document did not provide any means to open the drawer. On digging deeper into the code, noticed one method within the DrawerLayoutAndroid.android.js called openDrawer. This looked to be promising but the challenge was this was withing the Component, but react provides a nice feature called ref which is a callback function that is executed after render returning an instance of the rendered component. By using this i was able to access the openDrawer method and open the menu as required.

The below code snippet will explain this better:
var MenuDrawerLayout = React.createClass({
    navigationView : function(){
        return (
             <View style={{flex: 1,alignItems: 'center'}}>
                <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
                <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
              </View>
               );
    },
    drawerInstance : {instance : {openDrawer : function(){}}},
    initInstance : function(instance){
        console.log(instance);
        this.drawerInstance.instance = instance;
    },
    onMenuClick : function(event){
        //callback function called when menu is clicked. This
       console.log(this.drawerInstance.instance);
    this.drawerInstance.instance.openDrawer();
    },
    render:function(){
        return(<DrawerLayoutAndroid
            drawerWidth={dimension.width-56}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            ref={this.initInstance}
            renderNavigationView={this.navigationView}>
               <View style={styles.container} >
                    <View style={[styles.body]}>
                        <Header onMenuClick={this.onMenuClick}></Header>
                        <Dashboard.DashboardBody />
                    </View>
               </View>
        </DrawerLayoutAndroid>);
    }
})



No comments:

Post a Comment