Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active November 13, 2017 03:30
Show Gist options
  • Save jossmac/94bc58f55ac32d9da51643756cb91e58 to your computer and use it in GitHub Desktop.
Save jossmac/94bc58f55ac32d9da51643756cb91e58 to your computer and use it in GitHub Desktop.
A HOC for moving props to context. Used as a conduit to maintain context when rendering to a different subtree.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
const DefaultBaseComponent = props => <div {...props} />;
const withContextFromProps = (
propTypes: PropTypes.object,
BaseComponent: PropTypes.func = DefaultBaseComponent
) => {
class ContextProps extends Component {
static propTypes = { children: PropTypes.node }
getChildContext() {
const props = Object.keys(this.props).reduce((result, key) => {
if (key !== 'children') result[key] = this.props[key];
return result;
}, {});
return props;
}
render() {
return <BaseComponent>{this.props.children}</BaseComponent>;
}
}
ContextProps.displayName = 'withContextFromProps';
ContextProps.childContextTypes = propTypes;
return ContextProps;
};
export default withContextFromProps;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment