I'm using react-navigation in my project and I need to toggle a modal on right header button click. When I setState to true, I get undefined.
Code:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { ToggleDrawer, ToggleAdditional } from '../../utils';
import { AdditionalModal } from '../../components';
class Settings extends Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: 'Profile',
headerLeft: <ToggleDrawer pressHandler={() => navigation.openDrawer()} />,
headerRight: (
<ToggleAdditional pressHandler={() => params.handleAdditionalModal()} />
)
};
};
constructor(props) {
super(props);
this.state = {
modalIsVisible: false
};
}
componentDidMount() {
const { navigation } = this.props;
navigation.setParams({
handleAdditionalModal: this.toggleAdditionalModal
});
}
toggleAdditionalModal() {
this.setState({
modalIsVisible: true
});
}
render() {
const { modalIsVisible } = this.state;
return (
<View>
<Text>Settings</Text>
<AdditionalModal isVisible={modalIsVisible} />
</View>
);
}
}
export default Settings;
What am I doing wrong and what's the best way to handle such click events in react-navigation header?
Thanks!
try using arrow function for toggleAdditionalModal
toggleAdditionalModal = () =>{
this.setState({
modalIsVisible: true
});
}
you need arrow function because you want to access this
property, which refers to the current class.
Arrow functions means that this
will not refer to the context of your function but to the context of the class.
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