Skip to content

Instantly share code, notes, and snippets.

@chrismllr
Created October 30, 2017 20:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrismllr/92c3a314d7d035c8877fcf672cfd555c to your computer and use it in GitHub Desktop.
Save chrismllr/92c3a314d7d035c8877fcf672cfd555c to your computer and use it in GitHub Desktop.
react-native-navigation: navigation handler HOC
/* Usage
const navigationHandlers = [
{
predicate: props => props.currentUser.isAuthenticated === false,
handler: navigator => {
navigator.resetTo({
screen: LOGIN_SCREEN,
animationType: 'fade'
});
}
}
];
export defualt withNavigationHandlers(navigationHandlers)(Home)
*/
// @flow
import * as React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import get from 'lodash.get';
type WrappedProps = {
navigator: Object,
[propKey: string]: any
};
type Definition = {
predicate: (props: WrappedProps) => boolean | string,
handler: (navigator: Object) => void
};
export function handleNavigateForPredicate(props: WrappedProps) {
return function handle(definition: Definition) {
const { handler, predicate } = definition;
const getFromProps = typeof predicate === 'string';
const usePredicate = !getFromProps;
let shouldNavigate;
if (getFromProps) {
shouldNavigate = get(props, predicate) === true;
}
if (usePredicate) {
shouldNavigate = predicate(props);
}
if (shouldNavigate) {
handler(props.navigator);
}
};
}
export default function withNavigationHandlers(allHandlers: Array<Definition>) {
return (WrappedComponent: React.ComponentType<WrappedProps>) => {
class EnhancedComponent extends React.Component<WrappedProps> {
props: WrappedProps;
static displayName = `withNavigationHandler(${WrappedComponent.displayName})`;
componentDidMount() {
allHandlers.forEach(handleNavigateForPredicate(this.props));
}
componentWillReceiveProps(nextProps) {
allHandlers.forEach(handleNavigateForPredicate(nextProps));
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistStatics(EnhancedComponent, WrappedComponent);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment