I have this below where I fetched country's names from an API, and displayed them on the screen using routes
. Now, I'd like to display item.country
as the headerTitle
. However, I am getting an undefined
error for the route.params.
How can I fix this?
LocationDataScreen.tsx
function LocationDataScreen({ route, navigation }) {
const { item } = navigation.state.params || {};
const countryName = item.country;
return (
<View style={styles.container}>
<Text>{countryName}</Text>
<Text>{item.cases}</Text>
</View>
);
}
ItemView.tsx
const ItemView = ({ item }) => {
return (
<RectButton
onPress={() =>
navigate("LocationDataScreen", { item: item, name: item.country })
}
>
<Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
{item.id}
{item.country.toUpperCase()}
</Text>
</RectButton>
);
};
App.tsx
<AppStack.Navigator initialRouteName="SearchScreen">
<AppStack.Screen name="SearchScreen" component={SearchScreen} />
<AppStack.Screen
name="LocationDataScreen"
component={LocationDataScreen}
options={({ route }) => ({
headerLargeTitle: true,
title: route.params.item,
})}
/>
The issue is simply that you are passing params to LocationDataScreen.tsx
in a wrong manner.
Use this instead:
ItemView
const ItemView = ({ item }) => {
return (
<RectButton
onPress={() =>
navigate("LocationDataScreen", { ...item })
}
>
<Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
{item.id}
{item.country.toUpperCase()}
</Text>
</RectButton>
);
};
LocationDataScreen.tsx
function LocationDataScreen({ route, navigation }) {
const { country, cases } = route.params
return (
<View style={styles.container}>
<Text>{country}</Text>
<Text>{cases}</Text>
</View>
);
}
I am assuming here that your item in this line const ItemView = ({ item }) => {
looks something like this.
item: {
country: 'Italy',
cases: 10
}
If you could add your api response here. Let me know in the comments once you have added. Also share the link to the same in the comment.