Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation header onPress - this.setState is not a function

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!

like image 282
lecham Avatar asked Mar 05 '23 05:03

lecham


1 Answers

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.

like image 145
AlexZvl Avatar answered Mar 16 '23 01:03

AlexZvl