Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 40thieves/acd28e73e3315eeebccb6370b69ec025 to your computer and use it in GitHub Desktop.
Save 40thieves/acd28e73e3315eeebccb6370b69ec025 to your computer and use it in GitHub Desktop.
Custom ESLint rule to catch a footgun in JSX when using && operator with array length comparison
/*
* Catches this footgun:
*
* {myArray.length && (
* <div>Foo</div>
* )}
*
* which renders "0" if myArray is empty
*
* It should instead be:
*
* {myArray.length > 0 && (
* <div>Foo</div>
* )}
*
* or a ternary
*
*/
module.exports = {
rules: {
'prevent-jsx-array-length-and-operator-without-comparison': {
create: function (context) {
return {
JSXExpressionContainer(node) {
if (
node.expression.type === 'LogicalExpression' &&
node.expression.operator === '&&' &&
node.expression.left.type === 'MemberExpression' &&
node.expression.left.property.name === 'length'
) {
context.report({
node: node.expression.left,
message:
'Do not use array.length conditional in && operator without comparison in JSX'
})
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment