Created
August 12, 2017 23:22
-
-
Save pnegahdar/3e673c816ec631f556c591be50330638 to your computer and use it in GitHub Desktop.
contexDefaultProps.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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