Search code examples
react-nativereact-navigationreact-navigation-stackreact-navigation-drawer

ReactNative Cannot update a component from inside the function body of a > different component


My HomeHeader component is like this:

import React from "react";
import { View, StyleSheet, Text, Image } from "react-native";
import Icon from "react-native-vector-icons/FontAwesome5";

export default function HomeHeader({ navigation }) {
  return (
    <View style={styles.home_header}>
      <Icon
        style={styles.menu}
        name="bars"
        size={30}
        color="white"
        onPress={navigation.toggleDrawer()}
      />

      <Image
        style={styles.header_logo}
        source={require("../assets/logo.png")}
      />
      <Text>Hello</Text>
    </View>
  );
}

And am using it in my Home screen like this:

return (
  <View>
    <HomeHeader navigation={navigation} />
  </View>
)

But am receiving this error message:

Warning: Cannot update a component from inside the function body of a different component.

What am trying to do is, I have separated out the header section of my HOME screen into a separate component called HomeHeader. And in this component, am attaching the event handler to toggle the opening/closing of the DrawerNavigation (left side drawer menu)

If I create a Button in my HOME screen and add the event handler to toggle the drawer, it works fine. But the issue happens only if I try this from inside my HomeHeader component.

Btw, am using ReactNavigation v5 and I even tried this method: https://reactnavigation.org/docs/connecting-navigation-prop/

No luck so far.


Solution

  • Change onPress={ navigation.toggleDrawer() } to onPress={ ()=> navigation.toggleDrawer() }

    You can read more about this in here