Pass eslint html-has-for with htmlFor in React

Viewed 14708

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?

3 Answers

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
 }

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.

Related