Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access params passed to a class based component in react navigation 5.0?

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?

like image 496
Nathan Dullea Avatar asked Dec 11 '22 01:12

Nathan Dullea


1 Answers

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

like image 132
Harshal Bhavsar Avatar answered Apr 26 '23 18:04

Harshal Bhavsar