Using react-navigation you can pass parameters like this:
this.props.navigation.navigate(screen, {param: value});
and in previous versions you could access the parameters like this:
props.navigation.state.params
In the new version of react-navigation (5.0) they use functional components, and it appears you cannot access the params as you did before. Instead, you write components and access params like this:
function HomeScreen({ navigation, route }) {
React.useEffect(() => {
if (route.params?.post) {
// Post updated, do something with `route.params.post`
// For example, send the post to the server
}
}, [route.params?.post]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Create post"
onPress={() => navigation.navigate('CreatePost')}
/>
<Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>
</View>
);
}
How can I access the parameters passed to a component, without having to change all of the components in a project from class-based to functional-based components?
You just have change the code you used to access params from
props.navigation.state.params
to
props.route.params
All will be good no need to change class-based to functional-based components.
But i will suggest you start migrating at your own ease so you code will be as per the latest syntax.
You can see an example of this with the snippet here on this Expo snack here on this Expo snack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With