Created
July 8, 2020 13:47
-
-
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
This file contains hidden or 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
/* | |
* 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