Skip to content

Instantly share code, notes, and snippets.

@egeste
Created November 12, 2018 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egeste/8d851bf09d3db06f31f3bb0ab95c7d67 to your computer and use it in GitHub Desktop.
Save egeste/8d851bf09d3db06f31f3bb0ab95c7d67 to your computer and use it in GitHub Desktop.
Proptype enforcement decorator
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
}
}
}
@taverasmisael
Copy link

Brilliant utility. Does this take into consideration the Props that are not required, or does it enforces all props?

@egeste
Copy link
Author

egeste commented May 17, 2022

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