Home > front end >  How do I pass the props to DrawerItem Component?
How do I pass the props to DrawerItem Component?

Time:10-31

I am trying to build a Navigation Drawer using React-Native and this is my DrawerItem component

<DrawerItem
  icon={({ color, size }) => (
    <MaterialCommunityIcons name="home-outline" size={30} color={colors.medium} />
  )}
  label="Home"
  onPress={() => {
    props.navigation.navigate("HomeScreen");
  }}
/>

Since This component is being used several times in my drawer, I would like to create a Custom component like so

function AppDrawerItem({ label, ScreenName, icon, color = "medium" }) {
  return (
    <DrawerItem
      icon={({ color, size }) => (
        <MaterialCommunityIcons name={icon} size={30} color={colors[color]} />
      )}
      label={label}
      onPress={() => {
        props.navigation.navigate[ScreenName];
      }}
    />
  );
}

export default AppDrawerItem;

When I try to implement this I am getting the following error

enter image description here

How do I pass the ScreenName as props?


This is how I am calling my custom-component

<DrawerContentScrollView {...props}>
  <Drawer.Section style={styles.mainSection}>
    
    <AppDrawerItem
      label="Home"
      ScreenName="HomeScreen"
      icon="home-outline"
    />
  </Drawer.Section>
</DrawerContentScrollView>

CodePudding user response:

The problem is not with your ScreenName prop.

You already destructured the props parameter as

{ label, ScreenName, icon, color = "medium" } which is why it can't find props variable.

What you can do is like this:

function AppDrawerItem({ label, ScreenName, icon, color = "medium", ...props}) {
//...
}

In this way you can access the props variable.

Also as you creating a Custom DrawerItem called AppDrawerItem, you will also need to pass the navigation prop to it.

Do it like this:

<AppDrawerItem
      label="Home"
      ScreenName="HomeScreen"
      icon="home-outline"
      navigation={props.navigation}
    />
  • Related