Created
November 12, 2018 19:47
-
-
Save egeste/8d851bf09d3db06f31f3bb0ab95c7d67 to your computer and use it in GitHub Desktop.
Proptype enforcement decorator
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, { | |
PureComponent | |
} from 'react' | |
export default ComposedComponent => { | |
return class EnforcedPropTypesComponent extends PureComponent { | |
// Expose the composed component's propTypes at the decorator level | |
static propTypes = ComposedComponent.propTypes | |
// Determine whether or not the component's propTypes interface is fulfilled | |
shouldRender = () => { | |
// See `node_modules/prop-types/checkPropTypes` for more info | |
for (var typeSpecName in ComposedComponent.propTypes) { | |
const typeSpec = ComposedComponent.propTypes[typeSpecName] | |
if (ComposedComponent.propTypes.hasOwnProperty(typeSpecName)) { | |
try { | |
const error = typeSpec(this.props, typeSpecName, ComposedComponent.name) | |
if (error) { | |
if (process.env.NODE_ENV !== 'production') { | |
console.info(`Will not render ${ComposedComponent.name}`, error) | |
} | |
return false | |
} | |
} catch(e) { | |
if (process.env.NODE_ENV !== 'production') { | |
console.error(`Will not render ${ComposedComponent.name}`, e) | |
} | |
return false | |
} | |
} | |
} | |
return true | |
} | |
render() { | |
return this.shouldRender() ? ( | |
<ComposedComponent { ...this.props } /> | |
) : null | |
} | |
} | |
} |
Brilliant utility. Does this take into consideration the Props that are not required, or does it enforces all props?
lol whoops. Only 2 years late 😅
IIRC, it should respect the isRequired and its inverse, yes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Brilliant utility. Does this take into consideration the Props that are not required, or does it enforces all props?