Skip to content

Instantly share code, notes, and snippets.

@janicduplessis
Last active October 23, 2018 04:21
Show Gist options
  • Save janicduplessis/8693535c50f2c45a7707e468a374339a to your computer and use it in GitHub Desktop.
Save janicduplessis/8693535c50f2c45a7707e468a374339a to your computer and use it in GitHub Desktop.
// @flow
import React from 'react';
import { StatusBar } from 'react-native';
import hoistStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
import { withNavigation } from 'react-navigation';
import type { Subscription } from '../../types';
type Config = {
barStyle?: 'default' | 'light-content' | 'dark-content',
hidden?: boolean,
};
// Version that doesn't render the StatusBar component, useful for advanced use cases.
export function withStatusBarNavigationFocus(Component: any) {
class ComponentWithStatusBar extends React.PureComponent<
any,
{ isFocused: boolean },
> {
static displayName = `withStatusBarNavigationFocus(${Component.displayName ||
Component.name})`;
state = {
isFocused: true,
};
_subscriptions: ?Array<Subscription>;
componentDidMount() {
const { navigation } = this.props;
invariant(
!!navigation,
'withStatusBar can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context.',
);
this._subscriptions = [
navigation.addListener('willFocus', () =>
this.setState({ isFocused: true }),
),
navigation.addListener('willBlur', () =>
this.setState({ isFocused: false }),
),
];
}
componentWillUnmount() {
if (this._subscriptions != null) {
this._subscriptions.forEach(sub => sub.remove());
}
}
render() {
return <Component {...this.props} isFocused={this.state.isFocused} />;
}
}
return hoistStatics(withNavigation(ComponentWithStatusBar), Component);
}
export default function withStatusBar(Component: any, config: Config) {
class ComponentWithStatusBar extends React.PureComponent<any> {
static displayName = `withStatusBar(${Component.displayName ||
Component.name})`;
render() {
const { isFocused, ...others } = this.props;
return (
<>
{isFocused && <StatusBar animated {...config} />}
<Component {...others} />
</>
);
}
}
return hoistStatics(
withStatusBarNavigationFocus(ComponentWithStatusBar),
Component,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment