Reputation: 621
I am building an app that has a list on the home screen routing to a number of other screens.
I created a list component that is rendered on the home page, and therefore, need to pass the navigation down to the list component. The list component, in turn, will determine which screen to display depending on which item is pressed.
I am using a Stack Navigator
on my router.js file
export const HomeStack = StackNavigator({
Home: {
screen: Home,
navigationOptions: {
title: 'Home',
},
},
Nutrition: {
screen: Nutrition,
navigationOptions: {
title: 'Nutrition',
}
},
});
In my home.js screen I have the below code inside the render method
render() {
return (
<View>
<View>
<ListComponent navigate={this.props.navigation.navigate('')} />
<Button
title="Go to Nutrition"
onPress={() => this.props.navigation.navigate('Nutrition')}
/>
</View>
</View>
);
}
The Button successfully routes to the Nutrition.js screen.
But, I try to get my ListComponent.js to handle where to route as this file maps through my list array.
render() {
return (
<List>
{ListData.map((listItem, i) => (
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={this.onPressHandler(listItem.title)}
/>
))}
</List>
);
}
How can I properly pass the navigation as props down to ListComponent.js and then use the title from the list array to determine which screen to display?
Upvotes: 0
Views: 436
Reputation: 1954
change this line :
<ListComponent navigate={this.props.navigation.navigate('')} />
to this :
<ListComponent navigate={(screen)=>this.props.navigation.navigate(screen)}/>
and change this
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={this.onPressHandler(listItem.title)}
/>
to this :-
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={()=>this.props.navigate(listItem.title)}
/>
As you are calling the method directly not binding it to the component.
I am assuming that your code in ListItem.js is correct.
Upvotes: 1