Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DrawerLayoutAndroid component for building drawer in react-native apps?

I am new to react native and I am trying to build hamburger drawer to assist in navigation. But I could not find proper documentation. I found one but it was with redux so I let it go. Can anybody guide me how to create drawerlayout for react-native apps?

like image 438
atif Avatar asked Mar 12 '23 19:03

atif


1 Answers

You can take help from below code sample : Your toolbar.js can be as:

'use strict';

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

var ToolbarAndroid = require('ToolbarAndroid');

class MyToolbar extends Component {
render() {
  var navigator = this.props.navigator;
   return (
    <ToolbarAndroid
     title={this.props.title}
     navIcon={require('./icons/ic_menu_white_24dp.png')}
     style = {styles.toolbar}
     titleColor={'white'} 
     onIconClicked={this.props.sidebarRef}/>
    );
 }

const styles = StyleSheet.create({
//define your own style
}  
 });

module.exports = MyToolbar;

And in for implementing drawer:

'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Navigator,
  TouchableHighlight,
  TouchableOpacity, 
  DrawerLayoutAndroid,
  ScrollView,
} from 'react-native';

var ToolbarAndroid = require('ToolbarAndroid');
var MyToolbar = require('./MyToolbar');
var MenuItem = require('./MenuItem');

class OpenDraweFromToolbar extends Component {
 render() {

  var navigationView = (
     <ScrollView>
  <View style = {{height:100, backgroundColor:'blue', justifyContent:'center'}}>
     <Text style = {{height:25, color:'white', fontSize:25, marginLeft:20}}>Welcome To ReactNative</Text>
  </View>
  <ListView
       //render your list items
  </ScrollView>
);

return (
  <DrawerLayoutAndroid
    drawerWidth={300}
    drawerPosition={DrawerLayoutAndroid.positions.Left}
    renderNavigationView={() => navigationView}
    ref={'DRAWER'}>     
    <MyToolbar style={styles.toolbar}
        title={'Calendar'}
        navigator={this.props.navigator}
        {sidebarRef={()=>this._setDrawer()}}/>                  
    <View style={{flex: 1, alignItems: 'center'}}>            
      <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>

    </View>
  </DrawerLayoutAndroid>  
);
}

 _setDrawer() {
   this.refs['DRAWER'].openDrawer();
  }  
 }

 const styles = StyleSheet.create({
   //your own style implementation

 });

  module.exports = OpenDraweFromToolbar;

You should pass drawerlayout opening method as props to toolbar and in your toolbar component you should call sidebarRef as props, which automatically call the drawerlayout opening method of previous OpenDraweFromToolbar.js.

I hope you will get help from the above sample.Happy coding !!!

like image 85
Riten Avatar answered Apr 03 '23 03:04

Riten