How to pass back param to parent screen on BackHandler in react-native?

813 Views Asked by At
"react": "16.13.1",
"react-native": "0.63.2",
"@react-navigation/bottom-tabs": "^5.7.3",
"@react-navigation/compat": "^5.2.5",
"@react-navigation/material-bottom-tabs": "^5.2.15",
"@react-navigation/material-top-tabs": "^5.2.15",
"@react-navigation/native": "^5.7.3",
"@react-navigation/stack": "^5.9.0",

I want to pass data back to parent screen when pressing back on device. But I got error:-

TypeError: undefined is not an object (evaluating 'this.props.navigation')

Handling going back on arrow header is not a problem. But on smartphone back button itself having this error.

MainItem.js

    onPressShowItem = (item, index) => {
        this.props.navigation.navigate('ItemDetails', { FlatData: this.state.FlatData, FlatIndex: index, returnFromItems: this.returnFromItems });
    }
    returnFromItems = data => {
        console.log('returned');
        this.setState({ data });
    }

ItemDetails.js

class ItemDetails extends PureComponent {
  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
  /// PART OF ERROR APPEAR
  handleBackButton() {
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
    return true;
  }
  // Handle back on header. No problem here
  navigateBack = () => {
    this.props.navigation.goBack();
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
  };
  render() {
    return (
    const RenderBackAction = () => (
      <TopNavigationAction icon={BackIcon} onPress={this.navigateBack} />
        <TopNavigation title='Item Details' alignment='center' accessoryLeft={RenderBackAction} />
    );
    );
  }
}

I have tried but end-up with the error:-

1. this.props.route.params.returnFromItems
2. this.props.navigation.state.params.returnFromItems
1

There are 1 best solutions below

1
On BEST ANSWER

You are missing the reference to 'this'

you can either bind it or change the function like below

handleBackButton=()=> {
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
    return true;
}

As you are returning true you will have to manage the going back on your own so the second method is preferred.

Also you can use the existing navigateBack there

handleBackButton=()=> {
    this.navigateBack();
    return true;
}