Search code examples
reactjsmaterial-uiaccessibilitylighthouse

Form elements do not have associated labels, but it is a MUI theme switch


I have a theme switch (light to dark) on my page, using Material UI switch. I get an error from lighthouse stating that it needs a label, but if I make a text label it will impact the design and make it worse. Are there any solutions to this? enter image description here

Also, here is the error from Lighthouse

enter image description here


Solution

  • Add an aria-label to the Switch:

    <Switch
      checked = {checked}
      onChange = {handleChange}
      inputProps = {{ 'aria-label': 'theme' }}
    />
    

    You may use other attributes in inputProps as well (e.g. aria-labelledby, title).

    One of the categories Lighthouse checks for is Accessibility. When certain elements like your Switch do not have an accessible name, an aria-label may be used to provide the element with an accessible name.