Skip to content

Instantly share code, notes, and snippets.

@congwenma
Last active February 9, 2022 11:58
Show Gist options
  • Save congwenma/36524db0fff6ec7625252b0cd0f198c2 to your computer and use it in GitHub Desktop.
Save congwenma/36524db0fff6ec7625252b0cd0f198c2 to your computer and use it in GitHub Desktop.
codemod: react 16 event prop warning if passes in boolean
/* eslint-disable */
const EVENT_NAMES = ['onMouseDown', 'onMouseUp', 'onClick', 'onKeyUp', 'onKeyDown']
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
let foundAttrs = j(file.source).find(j.JSXAttribute)
var replacements = []
foundAttrs = foundAttrs.forEach(path => {
const k = j; // codeshift api
var propsStartsWithOn = path.value.name.name.startsWith('on')
const isAmpConditional = path.value.value && path.value.value.expression && path.value.value.expression.type === 'LogicalExpression' && path.value.value.expression.operator === '&&'
if(path.value.name.name === 'onClick') { debugger }
if (!(propsStartsWithOn && isAmpConditional)) return;
var eventReplacer = `${j(path.value.value.expression.left).toSource()} ? ${j(path.value.value.expression.right).toSource()} : undefined`;
var callbackReplacer = `${j(path.value.value.expression.left).toSource()} ? ${j(path.value.value.expression.right).toSource()} : _.noop`;
var smartReplacer = eventReplacer
replacements.push(
[
`${path.value.name.name}={${j(path.value.value.expression).toSource()}}`,
`${path.value.name.name}={${smartReplacer}}`,
]
)
return true
})
var source = j(file.source)
.find(j.Identifier)
.toSource();
source = replacements.reduce((source, rep) => source.replace(rep[0], rep[1]), source)
debugger
return source
}
/* eslint-enable */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment