Reputation: 11
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.
Upvotes: 1
Views: 539
Reputation: 876
I tested some JSX code with eslint with your requirement, and it worked for me.
// 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
sources
Upvotes: 0
Reputation: 21
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
Upvotes: 1