Reputation: 143
I cant seem to figure how to pass variable with typescript in react native, I have tried the params but its saying undefined is not an object (evaluating 'navigation.props.value').
below are the codes.
import {useNavigation} from '@react-navigation/core';
const navigation = useNavigation();
.......
<TouchableOpacity onPress={() => navigation.navigate('NewsDetails', {value: 'hi', })}>
<Block row flex={0} align="center">
<Text
p
color={colors.link}
semibold
size={sizes.linkSize}
marginRight={sizes.s}>
Read Article
</Text>
<Image source={assets.arrow} color={colors.link} />
</Block>
</TouchableOpacity>
then to display it in screen be this is what I had done but its not working
<Text p marginBottom={sizes.s}>
{navigation.props.value}
</Text>
Upvotes: 1
Views: 3088
Reputation: 128
For me the other answers didn't work in TypeScript because there was no value
in route.params.value
. However the solution that worked for me to get the data was to call the valueOf
method like this:
const route = useRoute();
if(route.params != undefined){
const data = route.params.valueOf() as DataType; // insert fitting datatype for the object you give the navigate method
return (...);
}
else {
...
}
Upvotes: 0
Reputation: 9856
Since NewsDetails
is a screen where you can navigate to, it is handled by a navigator, thus the route
and the navigation
props are passed to this screen by the navigator. You can access this in your NewsDetails
component from the screen props directly as follows.
const NewsDetails = ({route}) => {
const value = route.params.value
return (...)
}
Upvotes: 0
Reputation: 533
React navigation pass variables as params, not props. You can pass it using hooks, but then you will need to use the useRoute hook to get the route in the next screen, then get it as route.params.value
const nextScreen = () => {
const route = useRoute()
return <Text>route.params.value</Text>
}
Please notice that you can pass the navigation and route props from the navigator stack, and then you shouldn't need to use hooks:
https://reactnavigation.org/docs/params/
https://reactnavigation.org/docs/use-route
Upvotes: 4