Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass eslint html-has-for with htmlFor in React

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?

like image 587
CaribouCode Avatar asked Nov 20 '17 22:11

CaribouCode


Video Answer


2 Answers

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

like image 175
devk Avatar answered Oct 31 '22 00:10

devk


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
 }
like image 23
Ihor Avatar answered Oct 31 '22 02:10

Ihor