react-toggle icon indicating copy to clipboard operation
react-toggle copied to clipboard

Enhancement: console.warn when no label is provided #12

Open tgfbikes opened this issue 7 years ago • 0 comments

This is an enhancement (idea from @aaronshaf) that will give a warning in the console if the developer does not provide standard label implementation, such as wrapping react-toggle component in a label, providing a label with a 'for' attribute that matches an id prop for a react-toggle component, etc.

Changes to the react-toggle component:

  • Added second ref to the root div (line 143).

    • The reference is needed to check for any ancestors that are labels, i.e. the case where a developer would wrap a react-toggle component in a label. How this check is performed is described below.
  • Added componentDidMount life cycle method (line 30).

    • Need access to both refs and since componentDidMount will only run once, costly operations (like recursively checking for a parent that's a label) are only performed once and not on a re-render/prop change.

Added utils:

  • checkForLabel

    • Takes react-toggle container div element and input element as arguments. Performs three checks to see if there is any associated label. Returns true if there is some sort of a label or will give the console warning.
  • hasParentLabel

    • Recursively climbs through parentNodes of elements (starting on the react-toggle container div parent) looking for a tagName prop equal to 'LABEL'. Returns true parentNode with a tagName of 'LABEL' or false otherwise.
    • CONCERN - This is a potentially costly operation, especially if there isn't a parent node that's a label and if the react-toggle component is deeply nested in the DOM.
  • hasIdThatMatchesLabelFor

    • Checks the case of a label having a 'htmlFor' attribute that matches a react-toggle input id. Returns true if a label's htmlfor attr matches the input's id, otherwise false.
  • hasArialLabelOrAriaLabelledbyAttr

    • Checks the react-toggle input element for either an aria-label or an aria-labelledby attribute. Returns true if the input does have either, otherwise false.

tgfbikes avatar Feb 06 '18 16:02 tgfbikes