Skip to content

Instantly share code, notes, and snippets.

@andria-dev
Last active November 30, 2018 00:30
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 andria-dev/5edd78eb4ff17e34b0f81aaf8e6fbd2f to your computer and use it in GitHub Desktop.
Save andria-dev/5edd78eb4ff17e34b0f81aaf8e6fbd2f to your computer and use it in GitHub Desktop.
A simple preact prop checker that uses custom functions to verify props.
import preact from 'preact';
function printWarning(message) {
message = `Warning: ${message}`;
if (typeof console !== 'undefined') {
console.error(message);
}
}
// installs global prop checker
if (process.env.NODE_ENV !== 'production') {
preact.options.vnode = vnode => {
const propTypes = vnode.nodeName.propTypes;
if (propTypes) {
for (const propName in propTypes) {
const propValue = vnode.attributes[propName];
const {
checker,
message=`Invalid prop on ${propValue}`,
isRequired=false
} = propTypes[propName];
if (propValue === undefined && isRequired) {
printWarning(`${propName} is required`);
} else if (!checker(propValue)) {
printWarning(message);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment