Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function as a param in react-navigation 5

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     }); }; 
like image 660
Ayan Avatar asked Feb 07 '20 13:02

Ayan


People also ask

How do you pass a function with parameters in react?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .

How do I pass props with navigate?

Pass data in route state on the Navigate component's state prop. And to access the route state on the target routed component use the useLocation hook access it.

How do you pass params in tab navigation in react native?

To pass params to tab navigator React Navigation 5, we create a context and set put the value we want in the context. Then any component inside the context provider can access the value. export const NetworkContext = React. createContext();


1 Answers

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);   } } 
like image 122
satya164 Avatar answered Sep 23 '22 00:09

satya164