Last active
November 30, 2018 00:30
-
-
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.
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 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