eslint jsx-a11y label must be associated with a control error

341 Views Asked by At

The <label> in this code is being rejected by the eslint jsx-a11y plugin:

A form label must be associated with a control. eslint(jsx-a11y/label-has-associated-control)

<div className="flex items-center">
    <input
        id="filter-mobile-color-1"
        name="color[]"
        value="beige"
        type="checkbox"
        className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
    />
    <label
        htmlFor="filter-mobile-color-1"
        className="ml-3 min-w-0 flex-1 text-gray-500"
    >
        Beige
    </label>
</div>

Screenshot:

VSCode error

As far as I can see I am matching the 'sibling' case for that rule:

In this case, use htmlFor and an ID to associate the controls.

<label htmlFor={domId}>Surname</label>
<input type="text" id={domId} />
1

There are 1 best solutions below

0
icc97 On

I'm pretty sure it came down to this:

The input needs to also be inside the label to satisfy the stricter form of the rule (which the airbnb config configures, for example).

eslint-plugin-jsx-a11y #718 (comment)

But at that point I gave up - I did confirm that if I put it inside the label then it stopped giving the error:

<div className="flex items-center">
    <label
        htmlFor="filter-mobile-color-1"
        className="ml-3 min-w-0 flex-1 text-gray-500"
    >
        <input
            id="filter-mobile-color-1"
            name="color[]"
            value="beige"
            type="checkbox"
            className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
        />
        Beige
    </label>
</div>

I just stopped using the example.