Options menu with sub-items — React Native
So, it’s been a long time since there’s no such exact package found to get the menu option & menu items in react-native.
So without wasting more time just started building my own component as per our requirements.
- A three-dot icon should be on top right corner.
- A modal should appear on click of the three-dot icon.
- The list of options should appear over modal.
- On clicking outside, the appearing modal should get closed.
Directly jumping into the code, with expecting that you’re much familiar with the state, props, components, also with react native basics.
import { ListItem } from 'react-native-elements'
import {StyleSheet,Text,Image,TouchableOpacity,View,TouchableWithoutFeedback,Button,Modal,} from "react-native";
import { responsiveFontSize, responsiveHeight, responsiveWidth } from "react-native-responsive-dimensions";export default class MyComponent extends React.Component {
constructor(props:any){
super(props);
this.state ={
showoption: false,
}
}render(){
return (<View style={{flex:1}}>
<Modal
transparent={true}
onRequestClose={() => this.setState({ showoption: false })}
visible={this.state.showoption}>
<TouchableOpacity
onPressOut={() => this.setState({ showoption: false })}
style={{width: responsiveWidth(100),height: responsiveHeight(100),backgroundColor: "rgba(0,0,0,0.2)"}}>
<TouchableWithoutFeedback>
<View
style={{alignSelf: "flex-end",backgroundColor: "white",paddingVertical: responsiveHeight(1),borderRadius: responsiveWidth(2),marginTop:responsiveHeight(8),alignContent:"flex-start",marginRight: responsiveWidth(4)}}>
{list.map((item, index) => {
return (
<ListItem
title={item.title}
leftElement={<Image style={{width: responsiveWidth(4), resizeMode:"contain"}} source={item.image}/>}
titleStyle={{fontFamily: FONTS.regular}}
bottomDivider={index +1 != list.length}
style={{ width: responsiveWidth(45) }}
onPress={() => this.handleOnPressFor(index)}
containerStyle={{paddingVertical:responsiveHeight(1)}}/>)})}
</View>
</TouchableWithoutFeedback>
</TouchableOpacity>
</Modal>
</View>)
}
}
So here’s the conclusion for what we’ve done so far, we have a state variable to control display or not to display our menu modal, & everything controlled with designs & css. The only thing I’ve not included is header part. Where three-dot icon willl appear on the right top corner.
Just create your options menu now, cheers