Custom drawer using React Navigation

September 24, 2017 0 Comments

Custom drawer using React Navigation

 

 

Configuring your app side menu in a React Native App

React Navigation is a powerful library that helps us create Stack navigation, Drawer navigation and Tab navigation in our React Native apps. To create a simple side menu all we need to do is create a DrawerNavigator and pass in the route configuration and drawer configuration.

The above code is the entry level component in my react native app. The routing in the app happens via the Router component which is defined as below.

This gives us a drawer navigator with a list of navigation items. The component essentially contains the DrawerNavigator from react-navigation. When rendered it looks like this:

However, this out of the box method does not give us many options to configure the menu items. While working on my project, I searched through the documentation and spent hours trying to figure out how to create nested menus or perform functions other than navigation. After much effort this is what I found.

React-Navigation provides us with contentComponent configuration option in the DrawerNavigatorConfig. The contentComponent option allows us to pass in our own custom component to render in the drawer.

For limited customisation we can use DrawerItems component provided by react-navigation in contentComponent. In case we want to update the styles of the drawer, make it scrollable or add a header/footer we can still achieve it by using the DrawerItems. It will handle the navigation on its own. Below is an example of how to achieve it.

export default DrawerNavigator({
// ... your screens
}, {
// define customComponent here
contentComponent:
props =>
<ScrollView>
<DrawerItems {...props} />
<Text>Your Own Footer Area After</Text>
</ScrollView>
});

Complete customisation using contentComponent with Navigation actions to can be done in the following way:

The SideMenu is my custom component to be rendered in place of the default DrawerItems provided by the library. Inside the SideMenu:

The above example now allows me to create my own onPress functionality or add collapsible menu items as needed.

For sample app code check out: https://github.com/kakulgupta/CustomDrawer

That’s all folks!


Tag cloud