I am trying to use Menu from react native paper inside of my header but when pressing the button that is supposed to show the Menu, it doesn’t work, it simply does nothing. But when I do it outside of my header and I press the button that is supposed to show the menu it works and shows all the items as desired. Does anyone knows how I can fix that? Here is my code:
const [visible, setVisible] = React.useState(false);
const openMenu = () => setVisible(false);
const closeMenu = () => setVisible(false);
return (
<Drawer.Navigator initialRouteName="Home"
screenOptions={({ navigation }) => ({
headerStyle: {
backgroundColor: 'white',
},
headerTitleStyle: {
color: 'black',
},
headerLeft: () => <FontAwesome5 name='user-circle' style={{right: -15}} onPress={navigation.toggleDrawer} size={28} solid/>,
})}>
<Drawer.Screen name="Home" component={BottomTab}
options={{
title: '',
headerTitleAlign: 'center',
headerRight: () => (
<View>
<View style={{flexDirection: 'row'}}>
<View style={{left: -60}}>
<Provider>
<View
style={{
paddingTop: 0,
left: 0,
flexDirection: 'row',
textAlign: 'center',
top: 0,
}}>
<Menu
visible={visible}
onDismiss={closeMenu}
anchor={<Pressable onPress={openMenu}>
<Text style={{fontSize: 20, fontWeight: 'bold', backgroundColor: 'red', paddingRight: 30}}>
Popular
</Text>
</Pressable>}>
<Menu.Item onPress={() => {}} title="Item 1" />
<Menu.Item onPress={() => {}} title="Item 2" />
<Divider />
<Menu.Item onPress={() => {}} title="Item 3" />
</Menu>
</View>
</Provider>
{/*<Pressable onPress={() => console.log('Pressed Popular')}>
<Text style={{fontSize: 20, fontWeight: 'bold', backgroundColor: 'white', paddingRight: 30}}>
Popular
</Text>
</Pressable>*/}
</View>
<MaterialIcons
onPress={() => console.log('Pressed Popular')}
name="expand-more"
size={30}
style={{left: -80}}
/>
<Feather
onPress={() => props.navigation.navigate('Create')}
name="plus-circle"
color="black"
size={30}
style={{right: 15, top: 0}}
/>
</View>
</View>
),
}}
/>
2
Answers
I had the same issue, and it seems to work when you use setOptions in your Screen file combined with a useLayoutEffect.
How I fixed it is create the menu component outside the main component where the navigator is defined. Then pass all the necessary things as props to the menu component (and I think it works maybe because the re-render is not triggered in the older case).