Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props to Custom Drawer Navigator in React Navigation

In react navigation drawermenu. I want to display the username 'John Doe' which is in the state of my main component 'Router' How can I pass it the CustomDrawerContentComponent.

Extra Info: I'm getting this name from AsyncStorage in componentDidMount

This is my code

export default class Router extends Component {
  constructor(props) {
    super(props);
    this.state = {
      employeeName: "John Doe" //<-----How to pass this name to CustomDrawerContentComponent????
    };
  }

  render() {
    return <MyApp />;
  }
}

const MyApp = DrawerNavigator(
  {
    Home: {
      screen: Home
    },
    History: {
      screen: History
    },
    AddDetails: {
      screen: AddDetails
    }
  },
  {
    initialRouteName: "Home",
    drawerPosition: "left",
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: "DrawerOpen",
    drawerCloseRoute: "DrawerClose",
    drawerToggleRoute: "DrawerToggle",
    contentOptions: {
      activeTintColor: "#EF4036"
    }
  }
);

const CustomDrawerContentComponent = props => (
  <Container>
    <Header style={styles.drawerHeader}>
      <Body style={styles.container}>
        <Image
          style={styles.drawerImage}
          source={{
            uri: "http://themes.themewaves.com/nuzi/wp-content/uploads/sites/4/2013/05/Team-Member-3.jpg"
          }}
        />
        <Text style={styles.drawerText}>**How get the name here?**</Text>
      </Body>
    </Header>

    <Content>
      <DrawerItems {...props} />
    </Content>
  </Container>
);
like image 336
Ameer Hamza Avatar asked Jan 27 '23 16:01

Ameer Hamza


2 Answers

You can use screenProps:

<MyApp
  screenProps={{employeeName: this.state.employeeName}}
/>

And then use it in your custom contentComponent:

contentComponent:(props)=>(
  <View>
    <Text>{props.screenProps.employeeName}</Text>
    <DrawerItems {...props} />
  </View>
)

This is the answer for your question. But first of all I don't recommend using your top level component for such business logic. Use it only for navigation.

And see my answer here: Customizing Drawer

I recommend you to create a Redux connected custom drawer as I describe in my answer. If you don't know how to use Redux, I definitely recommend you to learn it. You will need it as your application grows.

like image 155
Sait Banazili Avatar answered Jan 31 '23 09:01

Sait Banazili


Just pass as screenprops

Render(){
return <Myapp screenprops={employeename:this.state.employeeName}/>;
}

You can access it from drawer like this this.props.screenprops.employeename

like image 41
vignesh Avatar answered Jan 31 '23 09:01

vignesh