React Navigation part 5: How to update params of a screen

Published by admin on

react-navigation part 5 update params of a screen

Introduction :

We may need to update the params of a screen. React navigation provides one method called setParams to do that. In this post, I will quickly show you how it works with an example.

 

Example project :

We will create one simple project with two screens. The first screen has one button, on click it will navigate to the second screen with a message parameter. The second screen will show that value.

The second screen also has one button, on click it will change the value of the parameter and that change will reflect on the screen.

 

Project Setup :

In this project, we have only two screens : FirstScreen.js and SecondScreen.js.

 

FirstScreen.js :

import {Text, View, Button} from 'react-native';
import React from 'react';

export default function FirstScreen({navigation}) {
  return (
    <View
      style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Text>First Screen</Text>
      <View style={{marginTop: 35}}>
        <Button
          title="Click me"
          onPress={() =>
            navigation.navigate('SecondScreen', {
              param: 'Hello from FirstScreen',
            })
          }
        />
      </View>
    </View>
  );
}

 

SecondScreen.js :

import {Text, View, Button} from 'react-native';
import React from 'react';

export default function SecondScreen({route, navigation}) {
  const {param} = route.params;

  return (
    <View
      style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Text>Second Screen</Text>
      <Text>{param}</Text>
      <View style={{marginTop: 35}}>
        <Button
          title="Click me"
          onPress={() => navigation.setParams({param: 'Changed'})}
        />
      </View>
    </View>
  );
}

 

The FirstScreen is the home screen. It passes one parameter param with a text to the second screen and we are showing that parameter value in the second screen. The button on the second screen changes the value of that param and the text will also change.

Categories: react-native

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *