Pass eslint html-has-for with htmlFor in React
Solution 1
In addition to setting an htmlFor
attribute and an id
the input element has to be nested inside the label.
You can, however, turn off the nesting requirement if you want. Something like this:
{
"extends": "airbnb",
"rules": {
"jsx-a11y/label-has-for": [ 2, {
"required": {
"every": [ "id" ]
}
}]
}
}
Issue related to your problem: https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/314
Docs: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
Solution 2
It seems like you've used it separately from your <input/>
tag. According to source docs you should put the <input/>
inside the <label/>
. Or you can set your .eslintrc like this
"rules": {
"jsx-a11y/label-has-for": 0
}
Solution 3
Eslint doesn't know about the input element that's being rendered elsewhere in your code. The error you're getting isn't complaining about the htmlFor
attribute per se, it's complaining that as far as it can tell, your htmlFor
doesn't refer to a form control element (ie- your input).
Try rendering the input alongside your label in the same component, this error should go away.
CaribouCode
Updated on July 29, 2022Comments
-
CaribouCode almost 2 years
I have a stateless React component that looks like this:
const propTypes = exact({ fieldId: PropTypes.string.isRequired, text: PropTypes.string.isRequired, }); function Label({ fieldId, text }) { return ( <label htmlFor={fieldId}>{text}</label> ); } Label.propTypes = propTypes;
I am using eslint extended with the airbnb config. My eslint looks like this:
{ "extends": "airbnb" }
My React code throws this error:
error Form label must have associated control jsx-a11y/label-has-for
I have clearly set an
htmlFor
attribute with a valid unique id string (which matches the id on an input elsewhere). Surely this is enough to pass this rule? -
CaribouCode over 6 yearsThanks for your input. I thought this might be the case so already tried what you suggest. Same error...
-
Titenis about 5 yearsif input has
name
attribute, it can be used for labelhtmlFor
attribute and lint will pass