I am trying to change the Header title of new component screen dynamically but getting the following error:
TypeError: TypeError: undefined is not an object (evaluating 'navigationData.navigation.getParam')
* screens\CategoryMealsScreen.js:26:42 in navigationOptions
* screens\CategoryMealsScreen.js:10:40 in CategoryMealsScreen
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:9473:27 in renderWithHooks
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11994:6 in mountIndeterminateComponent
My Code:
import React from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { CATEGORIES } from "../data/dummydata";
import Colors from "../constans/Colors";
let titleHeader = "";
const CategoryMealsScreen = props => {
const categoryId = props.navigation.getParam("categoryId");
const selectedCategory = CATEGORIES.find(cat => cat.id === categoryId);
CategoryMealsScreen.navigationOptions(selectedCategory.title);
// console.log(Object.keys(props.navigation));
titleHeader = selectedCategory.title;
return (
<View style={styles.screen}>
<Text>{selectedCategory.title}</Text>
<Button
title="Meals Details"
onPress={() => props.navigation.navigate("MealsDetail")}
/>
</View>
);
};
CategoryMealsScreen.navigationOptions = navigationData => {
const catId = navigationData.navigation.getParam("categoryId");
const selectedCategory = CATEGORIES.find(cat => cat.id === catId);
// console.log(catId);
// console.log(navigationData.navigation.getParam("categoryId"));
return {
headerTitle: selectedCategory.title,
headerStyle: {
backgroundColor: Colors.primaryColor
},
headerTintColor: "white"
};
};
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignContent: "center"
}
});
export default CategoryMealsScreen;
I tried to console log catId and it does show the output in the console but the error remains.
I am able to get data with getParam
inside the component but not in CategoryMealsScreen.navigationOptions
Some sited its problem with bable configuration but it is not working or I am doing something wrong.
Right not I am using global variable titleHeader
to change header title and it works but it's still a hack.
Problem occurs because of async task like find CATEGORIES.find(cat.. This will take a time to complete
Solution : use async/await with your fuction which wait for your task completion.
We can set title dynamically using navigationOptions directly in stack configuration.
CategoryMeals : {
screen : CategoryMealsScreen,
navigationOptions: ({ navigation }) => ({
title : navigation.getParam('categoryId', 'CategoryMeals')
}),
},