Skip to content

Instantly share code, notes, and snippets.

@AlexBrasileiro
Last active September 25, 2018 11:28
Show Gist options
  • Save AlexBrasileiro/49375e107365121a316bafc5e6e5477d to your computer and use it in GitHub Desktop.
Save AlexBrasileiro/49375e107365121a316bafc5e6e5477d to your computer and use it in GitHub Desktop.
React Native | Android Backbutton HOC
import React, { Component } from 'react';
import { BackHandler } from 'react-native';
const AndroidBackButton = (WrappedComponent) => {
return class extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.history.goBack() // for react-router-dom -> https://github.com/ReactTraining/react-router
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
render() {
return <WrappedComponent {...this.props} />
}
}
}
export default AndroidBackButton
// then use: withRouter(AndroidBackButton(YOURComponent))
@burdiuz
Copy link

burdiuz commented Sep 14, 2018

I don't see any reason of using HOC or wrapping any content into into this, it does not add anything to wrapped content. So in my opinion better implementation would be something like this.
Abstract button, that does not require using react-router or any other routing library. With it you are able to specify custom actions for back button.

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BackHandler } from 'react-native';

/**
 * To use provide onPress handler
 */
class AndroidBackButton extends Component {
  static propTypes = {
    onPress: PropTypes.func.isRequired,
  };

  componentDidMount() {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', (...args) => {
      const { onPress } = this.props;
      return onPress(...args);
    });
  }

  componentWillUnmount() {
    this.backHandler.remove();
  }

  render() {
    return null;
  }
}

export default AndroidBackButton;

Using with react-router, just put it anywhere you want this behavior <HistoryBackButton />.

export const HistoryBackButton = withRouter(({ history }) => (
  <AndroidBackButton
    onPress={() => {
      history.goBack();
      return true;
    }}
  />
));

I didn't run this code, so its more like pseudo code. :)

@AlexBrasileiro
Copy link
Author

@burdiuz perfect approach to ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment