Skip to content

Instantly share code, notes, and snippets.

@pnegahdar
Created August 12, 2017 23:22
Show Gist options
  • Save pnegahdar/3e673c816ec631f556c591be50330638 to your computer and use it in GitHub Desktop.
Save pnegahdar/3e673c816ec631f556c591be50330638 to your computer and use it in GitHub Desktop.
contexDefaultProps.js
import React from "react";
import PropTypes from "prop-types";
export function withContextDefaults(WrappedComponent) {
return class extends React.Component {
// Make sure context field contextName is in the child so it recieves the context
static contextTypes = {...WrappedComponent.contextTypes || {}, contextName: PropTypes.string}
componentWillMount() {
const contextDefaultProps = (WrappedComponent.contextDefaultProps && WrappedComponent.contextDefaultProps[this.context.contextName]) || {}
this.newProps = {...this.props, ...contextDefaultProps}
}
render() {
return <WrappedComponent {...this.newProps}/>;
}
}
}
@withContextDefaults
class PrintName extends React.Component{
propTypes = {
name: PropTypes.string.isRequired
}
contextDefaultProps = {
test: {
name: 'John Doe'
}
}
render = () =>
<p>Hello {this.props.name}</p>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment