javascriptreactjsjsxeslint

How to get eslint to select jsx elements that have a className with a particular class?


I am implementing eslint, and I am using 'no-restricted-syntax' to create custom selections my selection looks like this:

  'no-restricted-syntax': [
    'error',
    {
      selector: 'JSXElement JSXAttribute JSXIdentifier[name="className"] + Literal[value="bg-red"]',
      message: 'Do not set background colors directly.',
    },
  ],

I am testing the code on this test component, and it isn't finding the error:

export function TestComponent() {
  return <button className="bg-red">Click me</button>;
}

I have also tried modifying my selector to these without luck:

// On the attribute
JSXElement JSXAttribute[name="className"][value="bg-red"]

// removing the + Literal
JSXElement JSXAttribute JSXIdentifier[name="className"][value="bg-red"]

How can I get eslint to select jsx elements that have a className containing a particular class (or even better a class that starts with bg)?

If it helps, here is the ESLint explorer


Solution

  • Looking at the given [ESLint explorer][1] in json,

    The selector should be JSXAttribute[name.name="className"][value.value instead of JSXAttribute[name="className"][value=

    {
      "name": {
        "type": "JSXIdentifier",
        "start": 46,
        "end": 55,
        "name": "className"
      },
      "value": {
        "type": "Literal",
        "start": 56,
        "end": 64,
        "value": "bg-red",
        "raw": "\"bg-red\""
      }
    }