zedArt
zedArt

Reputation: 487

call functions when the uer opens drawer (onClick button or slide)

I had create a drawer system with react-navigation (without using DrawerLayoutAndroid) and I open it with a button or slide it What I want is to call function when the user opens the drawer and my function will change something in UI drawer, it will check if there is a new message or not to set new message notification icon! this is drawer navigation code:

const DrawerNavigation = createDrawerNavigator({
      Home: {
        screen: HomeStackNavigation,
      },
      Login: {
        screen: Login,
        navigationOptions: {
          header: null,
        }
      },
  },
  {
    drawerWidth: width*0.83,
    contentComponent: props =>
    {
      return(<DrawerComponent  {...props}/>)
    },
    drawerPosition: 'left',
  },
  );
export default createAppContainer(DrawerNavigation)

and drawer layout code it only a scrollView with items..

and this is a button code to open and close drawer in a home screen:

  toggleButtonDrawer = () => {
    this.props.navigation.openDrawer();
  }

I call it here:

  <View style={Styles.buttonMunuContainer}>
    <TouchableOpacity style={Styles.buttonMunu} onPress= {this.toggleButtonDrawer}>
    <IconAD name="menu-fold" size={ hp('4%')} color='white'/>
    </TouchableOpacity>
  </View>

PS. if you have another solution to set notification icon (+1) when a new message is received knowing that I don't use redux

pS. I work only on Android

Upvotes: 1

Views: 2393

Answers (2)

Mateus Enrick Pitura
Mateus Enrick Pitura

Reputation: 51

I researched the drawer navigation documentation (https://reactnavigation.org/docs/drawer-based-navigation) and found the following:

import { useDrawerStatus } from '@react-navigation/drawer';

// ...

const isDrawerOpen = useDrawerStatus() === 'open';

This way, you can combine it with useEffect like this:

useEffect(() => {
    if(isDrawerOpen){
        //yourFunction();
    }
}, [isDrawerOpen]);

This worked for me, so when I open the drawer (with a button or sliding) a function is called

Upvotes: 1

remeus
remeus

Reputation: 2469

In your custom drawer component <DrawerComponent />, you can use componentDidUpdate to detect when the drawer is opened.

componentDidUpdate(prevProps) {
  if (!prevProps.navigation.state.isDrawerOpen && this.props.navigation.state.isDrawerOpen) {
    console.log('The drawer has been opened!')
  }
}

So all you have to do is to fetch your messages at this time and compare with the current state of the component to check if there is any new notification to display.

Upvotes: 1

Related Questions