skip to Main Content

I want to apply eslint rule for JSX attribute value.
like I have a component having some attribute for example

<Component
  attribute1="abc-efg"
/>

In above example I want to place a rule which will check that if attribute1 is having values in lower-case and kebab-case if the value is other then that error will be thrown.

I tried: @typescript-eslint/naming-convention
but not able to achieve anything.

2

Answers


  1. To enforce a rule that checks if JSX attribute values are in lowercase and kebab-case, you can create a custom ESLint rule using the eslint-plugin and @typescript-eslint libraries. Here’s how you can set it up:

    // .eslintrc.js or eslint.config.js
    
    module.exports = {
      // Other ESLint configurations
      plugins: ['@typescript-eslint'],
      overrides: [
        {
          files: ['*.tsx', '*.jsx'], // Apply rule to JSX and TSX files
          rules: {
            'jsx-attributes/lowercase-kebab-case': ['error', { allowedAttributes: ['attribute1'] }],
          },
        },
      ],
    };
    

    After setting up the rule, run ESLint in your project to enforce the rule:
    eslint –ext .jsx,.tsx src

    Login or Signup to reply.
  2. I tested some JSX code with eslint with your requirement, and it worked for me.

    file structure

    // enforce-foo-bar.js
    
    module.exports = {
      meta: {
        type: 'problem',
        docs: {
          description:
            "This rule enforces that the value of the attribute is in kebab case or camel case",
        },
        fixable: 'code',
        schema: [],
      },
      create(context) {
        return {
          JSXOpeningElement(node) {
            const attributes = node.attributes;
    
            if (attributes.length > 0) {
              for (const element of attributes) {
                const attributeValue = element.value.value;
    
                if (attributeValue) {
                  if (
                    attributeValue.match(/^[a-z][a-zA-Z0-9]*$/) ||
                    attributeValue.match(/^[a-z][a-z0-9-]*$/)
                  ) {
                    context.report({
                      node: element,
                      message: 'Value in kebab case or camel case',
                    });
                  }
                }
              }
            }
          },
        };
      },
    };
    
    // eslint-plugin-example.js:
    
    const fooBarRule = require('./enforce-foo-bar');
    const plugin = { rules: { 'enforce-foo-bar': fooBarRule } };
    module.exports = plugin;
    
    // eslint.config.js:
    
    'use strict';
    
    const eslintPluginExample = require('./eslint-plugin-example');
    
    module.exports = [
      {
        files: ['**/*.jsx'],
        languageOptions: {
          sourceType: 'module',
          ecmaVersion: 'latest',
          parserOptions: {
            ecmaFeatures: {
              jsx: true,
            },
          },
        },
    
        plugins: { example: eslintPluginExample },
        rules: {
          'example/enforce-foo-bar': 'error',
        },
      },
    ];
    
    
    // Greeting.jsx
    
    import React from 'react';
    
    export default function Greeting({ name, age, location }) {
      return (
        <div>
          <p>Hello, {name}!</p>
          <p>Age: {age}</p>
          <p>Location: {location}</p>
        </div>
      );
    }
    
    // Test.jsx
    
    import React from 'react';
    import Greeting from './Greeting';
    
    export default function Test() {
      return (
        <div>
          <h1>Down</h1>
          <Greeting name='John' location='new-york' age={30}  />
        </div>
      );
    }
    

    After setting up the file structure, run npx eslint Test.jsx

    lint validation

    sources

    1. https://eslint.org/docs/latest/extend/custom-rule-tutorial
    2. https://blog.maximeheckel.com/posts/how-to-build-first-eslint-rule/
    3. https://astexplorer.net/
    4. https://eslint.org/docs/latest/rules/no-control-regex
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search