Passing function as a param in react-navigation 5

Ayan picture Ayan · Feb 7, 2020 · Viewed 8.2k times · Source

NOTE: This query is for react-navigation 5.

In react navigation 4 we could pass a function as a param while navigating but in react navigation 5, it throws a warning about serializing params.

Basically, what I am trying to do is, navigate to a child screen from parent screen, get a new value and update the state of the parent screen.

Following is the way I am currently implementing:

Parent Screen

_onSelectCountry = (data) => {
    this.setState(data);
};
.
.
.

<TouchableOpacity
    style={ styles.countrySelector }
    activeOpacity={ 0.7 }
    onPress={ () => Navigation.navigate("CountrySelect",
        {
             onSelect: this._onSelectCountry,
             countryCode: this.state.country_code,
        })
    }
>
.
.
.
</TouchableOpacity> 

Child Screen

_onPress = (country, country_code, calling_code) => {
    const { navigation, route } = this.props;
    navigation.goBack();
    route.params.onSelect({
        country_name: country,
        country_code: country_code,
        calling_code: calling_code
    });
};

Answer

satya164 picture satya164 · Feb 7, 2020

Instead of passing the onSelect function in params, you can use navigate to pass data back to the previous screen:

// `CountrySelect` screen
_onPress = (country, country_code, calling_code) => {
  const { navigation, route } = this.props;
  navigation.navigate('NameOfThePreviousScreen', {
    selection: {
      country_name: country,
      country_code: country_code,
      calling_code: calling_code
    }
  });
};

Then, you can handle this in your first screen (in componentDidUpdate or useEffect):

componentDidUpdate(prevProps) {
  if (prevProps.route.params?.selection !== this.props.route.params?.selection) {
    const result = this.props.route.params?.selection;

    this._onSelectCountry(result);
  }
}