Skip to content

Instantly share code, notes, and snippets.

@Liampronan
Last active August 21, 2019 19:47
Show Gist options
  • Save Liampronan/d211a3bdf9af575dc951cefdb1eaa32f to your computer and use it in GitHub Desktop.
Save Liampronan/d211a3bdf9af575dc951cefdb1eaa32f to your computer and use it in GitHub Desktop.
React Navigation: Nested Stack Navigators Workaround
import React, { Component } from "react";
import { compose } from "redux";
import hoistNonReactStatic from "hoist-non-react-statics";
/* eslint-disable no-restricted-imports */
import { withNavigationFocus } from "react-navigation";
import PropTypes from "prop-types";
// withTrackOnNavigationFocus fixes an issue with neseted stack navigators. we use this instead of
// directly calling withNavigationFocus so that nested stack navigators have correct isFocused prop.
function withNestedStackNavigationFocus(WrappedComponent) {
class ComponentWithNestedNavigationFocus extends Component {
static navigationOptions = WrappedComponent.navigationOptions;
constructor(props) {
super(props);
this.state = {
isFocused: false,
};
}
componentDidMount() {
this.focusListener = this.props.navigation.addListener("didFocus", () => {
this.setState({ isFocused: true });
});
this.blurListener = this.props.navigation.addListener("didBlur", () => {
this.setState({ isFocused: false });
});
}
componentWillUnmount() {
this.focusListener.remove();
this.blurListener.remove();
this.setState({ isFocused: false });
}
render() {
return <WrappedComponent {...this.props} isFocused={this.state.isFocused} />;
}
}
ComponentWithNestedNavigationFocus.propTypes = {
navigation: PropTypes.object,
};
// automatically copies all non-React static methods to this HOC. HOC's do not carry over any static methods of
// original component. in the context of nav components, this messes with static `navigationOptions` .
// (https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over)
hoistNonReactStatic(ComponentWithNestedNavigationFocus, WrappedComponent);
return ComponentWithNestedNavigationFocus;
}
export default compose(withNavigationFocus, withNestedStackNavigationFocus);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment