A <label> element should have text content and be associated with a control.
When a label element lacks text content or an associated control, it can lead to several issues:
Control elements include:
<input><meter><output><progress><select><textarea>Labels containing custom JSX components do not raise issues. Static analysis cannot determine whether a custom component eventually renders a control, so SonarJS treats it as an allowed exception.
Make sure the <label> has text that describes the control.
An implicit association wraps the control element inside the <label>. An explicit association keeps the label and control
separate, and links them with the label’s for attribute and the control’s id. Both approaches are compliant. If you lack a
control element, add one.
In JavaScript, this rule applies to JSX markup, so the examples below use JSX. In JSX, use htmlFor instead of for.
export function FavoriteFields() {
return (
<>
{/* Non-compliant: label without text */}
<label htmlFor="favorite-sport"></label>
<input id="favorite-sport" type="text" />
{/* Non-compliant: missing "htmlFor" attribute on label */}
<label>Favorite food</label>
<input id="favorite-food" type="text" />
</>
);
}
export function FavoriteFields() {
return (
<>
{/* Label with text */}
<label htmlFor="favorite-sport">Favorite sport</label>
<input id="favorite-sport" type="text" />
{/* Explicit association */}
<label htmlFor="favorite-food">Favorite food</label>
<input id="favorite-food" type="text" />
{/* Implicit association */}
<label>
Favorite place
<input id="favorite-place" type="text" />
</label>
</>
);
}