Passing function as a param in react-navigation 5
Passing a callback through react native navigation params is not recommended, this may cause the state to freeze (to not to update correctly). The better solution here would be using an EventEmitter, so the callback stays in the Screen1 and is called whenever the Screen2 emits an event.
Screen 1 code :
import {DeviceEventEmitter} from "react-native"
DeviceEventEmitter.addListener("event.testEvent", (eventData) =>
callbackYouWantedToPass(eventData)));
Screen 2 code:
import {DeviceEventEmitter} from "react-native"
DeviceEventEmitter.emit("event.testEvent", {eventData});
useEffect(() => {
return () => {
DeviceEventEmitter.removeAllListeners("event. testEvent")
};
}, []);
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);
}
}
There is a case when you have to pass a function as a param to a screen.
For example, you have a second (independent) NavigationContainer
that is rendered inside a Modal
, and you have to hide (dismiss) the Modal
component when you press Done inside a certain screen.
The only solution I see for the moment is to put everything inside a Context.Provider
then use Context.Consumer
in the screen to call the instance method hide()
of Modal
.