I'm setting the onPress function of a touchable in the header of my react-native application. this project uses react-navigation (v4) the function is to open the share dialog. it works perfectly in one component, and the same exact code does not work at all in the other component throwing an undefined error.
working screen:
class WorkingScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerRight: () => (
<TouchableOpacity onPress={navigation.state.params.onShare}>
<Image
source={require('../assets/img/white-share.png')}
style={{ height: 20, width: 20, marginRight: 20 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
)
}
}
{...}
componentDidMount() {
this.props.navigation.setParams({ onShare: () => this._onShare() })
}
_onShare = async () => {
const uid = this.props.navigation.getParam('uid')
const options = { title: uid, message: 'buggy af react-navigation' }
Share.open(options)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
}
{...}
}
working screen route config:
Working: {
screen: WorkingScreen,
navigationOptions: () => ({
title: 'Working'
})
}
non-working screen:
class NotWorkingScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerLeft: () => (
<TouchableOpacity onPress={() => navigation.toggleDrawer()}>
<Image
source={require('../assets/img/menu.png')}
style={{ marginLeft: 20, height: 20, width: 25 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
),
headerRight: () => (
<TouchableOpacity onPress={navigation.state.params.onShare}>
<Image
source={require('../assets/img/white-share.png')}
style={{ height: 20, width: 20, marginRight: 20 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
)
}
}
componentDidMount() {
this.props.navigation.setParams({ onShare: () => this._onShare() })
}
{...}
_onShare = async () => {
const uid = this.props.navigation.getParam('uid')
const options = { title: uid, message: 'buggy af react-navigation' }
Share.open(options)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
}
{...}
}
non-working screen route config:
NotWorking: {
screen: NotWorkingScreen,
navigationOptions: () => ({
title: 'Not Working'
})
}
the crash from the non working screen is:
TypeError: undefined is not an object (evaluating 'navigation.state.params.onShare')
They have identical stack configurations. I have no idea what's going on with this. Any ideas?