react navigation params

React Navigation Params

If you are building a React Native application and you want to pass data between screens, React Navigation Params is the way to go. Params allow you to pass data between screens, set up initial values for your screen components and control the behavior of your navigation flow.

Passing Params Between Screens

To pass params between screens, you can use the navigation.navigate function with an object containing the params you want to pass:

navigation.navigate('Profile', {
  userId: '123',
});

And then, in the receiving screen, you can access the params through the route.params object:

function ProfileScreen({ route }) {
  const { userId } = route.params;
  return (
    <View>
      <Text>User ID: {userId}</Text>
    </View>
  );
}

Setting Up Initial Params

You can also set up initial params for your screens using the initialParams prop in your screen component:

function ProfileScreen({ route }) {
  const { userId } = route.params;
  return (
    <View>
      <Text>User ID: {userId}</Text>
    </View>
  );
}

ProfileScreen.defaultProps = {
  route: {
    params: {
      userId: '456',
    },
  },
};

Controlling Navigation Behavior

You can also control the behavior of your navigation flow with params. For example, you can set up a param that determines whether a screen should be displayed or not:

navigation.navigate('Profile', {
  showProfile: true,
});

And then, in the receiving screen, you can use the useEffect hook to conditionally display the screen:

function ProfileScreen({ route }) {
  const { showProfile } = route.params;

  useEffect(() => {
    if (!showProfile) {
      navigation.goBack();
    }
  }, [showProfile]);

  return (
    <View>
      <Text>This is the profile screen!</Text>
    </View>
  );
}

These are just a few examples of what you can do with React Navigation Params. With params, you can build complex navigation flows and pass data seamlessly between screens.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe