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 }); };
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 .
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.
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();
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With