Skip to content

Commit

Permalink
[Fix] jsx-no-literals: properly handle HTML entities when allowed
Browse files Browse the repository at this point in the history
When an HTML entity such as — is checked with ESLint, the `value`
property becomes the actual unicode character instead of the raw
literal.

This means if `—` is in the allowed strings array, and `—`
is in the code being checked, the actual value used in the JSXText check
will be `—`, which will not match against `—`, so it causes a
false positive error.

When checking against the set of allowed strings, this will now check
both the `value` and the `raw` properties of the node. For `—`, the
`raw` property will still be `—`.

If _either_ of these match the list of allowed values, then no error
will be returned.

Fixes #3130

Co-authored-by: Joe Attardi <attardi@synopsys.com>
Co-authored-by: Ross <52366381+ROSSROSALES@users.noreply.github.com>
  • Loading branch information
2 people authored and ljharb committed Nov 11, 2021
1 parent 3963193 commit bdbd2a4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/rules/jsx-no-literals.js
Expand Up @@ -89,9 +89,11 @@ module.exports = {
}

function getValidation(node) {
if (config.allowedStrings.has(trimIfString(node.value))) {
const values = [trimIfString(node.raw), trimIfString(node.value)];
if (values.some((value) => config.allowedStrings.has(value))) {
return false;
}

const parent = getParentIgnoringBinaryExpressions(node);

function isParentNodeStandard() {
Expand Down
12 changes: 12 additions & 0 deletions tests/lib/rules/jsx-no-literals.js
Expand Up @@ -284,6 +284,18 @@ ruleTester.run('jsx-no-literals', rule, {
<img alt='blank image'></img>
`,
},
{
code: `
<div>&mdash;</div>
`,
options: [{ noStrings: true, allowedStrings: ['&mdash;', '—'] }],
},
{
code: `
<div>—</div>
`,
options: [{ noStrings: true, allowedStrings: ['&mdash;', '—'] }],
},
]),

invalid: parsers.all([
Expand Down

0 comments on commit bdbd2a4

Please sign in to comment.