Skip to content

Instantly share code, notes, and snippets.

@rafayepes
Forked from janicduplessis/withStatusBar.js
Created June 29, 2018 07:51
Show Gist options
  • Save rafayepes/2e7be4010779100faecffaf8d56f7c11 to your computer and use it in GitHub Desktop.
Save rafayepes/2e7be4010779100faecffaf8d56f7c11 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,
};
export default function withStatusBar(Component: any, config: Config) {
class ComponentWithStatusBar extends React.PureComponent<
any,
{ isFocused: boolean },
> {
static displayName = `withStatusBar(${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 (
<>
{this.state.isFocused && <StatusBar animated {...config} />}
<Component {...this.props} />
</>
);
}
}
return hoistStatics(withNavigation(ComponentWithStatusBar), Component);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment