Skip to content

Instantly share code, notes, and snippets.

@zeroFruit
Last active December 8, 2017 05:10
Show Gist options
  • Save zeroFruit/f770ee29b3f52e7117b719bc36b77a2c to your computer and use it in GitHub Desktop.
Save zeroFruit/f770ee29b3f52e7117b719bc36b77a2c to your computer and use it in GitHub Desktop.
// MyComponent.js
const renderHeader = (params) => <Header params={ params } />;
class MyComponent extends Component {
static navigationOptions = {
header: ({ navigation }) => renderHeaderWithNavigation(navigation)(renderHeader)
}
componentDidMount() {
const params = { ... };
setParamsToNavigation(this.props, params);
}
}
// Router.js
export const navigateTo = (props, to, params = {}) => {
props.navigation.navigate(to, params);
};
export const setParamsToNavigation = (props, params) => {
props.navigation.setParams({ ...params });
};
export const renderHeaderWithNavigation = (navigation) => {
const params = getParamsFromNavigationState(navigation.state);
return (renderHeaderMethod) => {
return renderHeaderMethod(params);
};
};
// recursive function
export const getParamsFromNavigationState = (state) => {
if (hasPath(state, 'index')) {
const { index, routes } = state;
return getParamsFromNavigationState(routes[index]);
} else {
return hasPath(state, 'params') ? state.params : null;
}
};
// mapNavigateParamsToPropsHOC.js
export const mapNavigateParamsToProps = (WrappedComponent) => {
return class MappedComponent extends Component {
static navigationOptions = WrappedComponent.navigationOptions;
render() {
const { navigation } = this.props;
const { state: { params } } = navigation;
return <WrappedComponent { ...this.props } { ...params } />;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment