Eslint Rule for Label
I Have a Problem My esLint Rules: "Jsx-A11Y/Label-Has-For": [ 2, { "Components": [], "Required": { "Every": [ "Nesting", "Id" ] }, "Allowchildren": True }], I...
i have a problem
My esLint rules:
"jsx-a11y/label-has-for": [ 2, {
"components": [],
"required": {
"every": [ "nesting", "id" ]
},
"allowChildren": true
}],
I want just for off this error, or fix, help me please
Error msg: A form label must be associated with a control. (jsx-a11y/label-has-associated-control)
JSX code:
<input
type="checkbox"
id="checkbox-2"
className="checkbox__input"
/>
<label
htmlFor="checkbox-2"
className="checkbox__label"
/>
4 Answers
I solved it by adding the below lines in my eslint file
{
....
"rules": {
"jsx-a11y/label-has-associated-control": ["error", {
"required": {
"some": ["nesting", "id"]
}
}],
"jsx-a11y/label-has-for": ["error", {
"required": {
"some": ["nesting", "id"]
}
}]
},
...
}
and don't forget to restart your local server after adding those lines.
it's only working when the label htmlFor(React) or for(HTML) and input id is matched.
<label htmlFor="temp-id">Label</label>
<input type="text" id="temp-id" />
Case 1: You can make input inside label
<label>
<input type="text"/>
</label>
case 2: use htmlFor
<label htmlFor="first-name">
First Name
</label>
<input type="text" id="first-name" />
you can go through the details of rules through this page:
Must Read
Edit:
According to docs:
Case: The label is a sibling of the control.
<label htmlFor={domId}>Surname</label>
<input type="text" id={domId} />
If you want just for off this warning you can add the special comment just before the line with the label:
<input type="text" id="myinput" />
<>{ /* eslint-disable-next-line jsx-a11y/label-has-associated-control */ }</>
<label htmlFor="myinput"></label>
Here you can find many other ESLint inline comments for disabling rules:
So first of all, for off this rule i needed to wrote this: "jsx-a11y/label-has-associated-control": "off",
then i need to off this: "jsx-a11y/label-has-for":"off",
And after all i needed to move it at the top of the file because in my case if i don`t move it to the top, my rule not worked.