Search code examples
reactjsaccessibilityjsx

react/jsx-a11y eslint throws unexpected errors for control/label


This code:

      <PopupContent>
        <label htmlFor="popup" style={{ margintop : '0px', marginbottom : '0px' }}>log out</label>
        <button type="button" id="popup" onClick={this.logUserOut} />
      </PopupContent>

throws these two errors:

 84:9  error  A form label must be associated with a control  jsx-a11y/label-has-associated-control
 85:9  error  A control must be associated with a text label  jsx-a11y/control-has-associated-label

What am I missing?


Solution

  • You don't typically use a element to label a button. More commonly, the text inside the button serves as its label. Try something along the lines of:

    <button type="button id="popup" onClick={this.logUserOut}>log out</button>
    

    Other options could be any one of the following:

    <button type="button" id="popup" onClick={this.logUserOut} aria-label="log out"/>
    

    or

    <span id="button-label" style={{ margintop : '0px', marginbottom : '0px' }}>log out</span>
    <button type="button" id="popup" onClick={this.logUserOut} aria-labelledby="button-label" />
    

    or

    <button type="button id="popup" onClick={this.logUserOut}>
        <img src="icon.png" alt="log out"/>
    </button>
    

    or

    <button type="button id="popup" onClick={this.logUserOut}>
        <span className="off-screen">log out</span>
    </button>
    

    where the CSS class of .off-screen hides the text off-screen in an accessible way e.g. do not use display: none; or visibility: hidden;