aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-attributes.tsx
blob: 35161edaa3f6267f5dee5035bdf71768f7a2f69f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useCallback, useEffect } from 'react';
import { fromKebabCaseToCamelCase } from '../helpers/strings';

export type useAttributesProps = {
  /**
   * An HTML element.
   */
  element?: HTMLElement;
  /**
   * A node list of HTML Element.
   */
  elements?: NodeListOf<HTMLElement> | HTMLElement[];
  /**
   * The attribute name.
   */
  attribute: string;
  /**
   * The attribute value.
   */
  value: string;
};

/**
 * Set HTML attributes to the given element or to the HTML document.
 *
 * @param props - An object with element, attribute name and value.
 */
const useAttributes = ({
  element,
  elements,
  attribute,
  value,
}: useAttributesProps) => {
  const setAttribute = useCallback(
    (el: HTMLElement) => {
      if (attribute.startsWith('data')) {
        el.setAttribute(attribute, value);
      } else {
        const camelCaseAttribute = fromKebabCaseToCamelCase(attribute);
        el.dataset[camelCaseAttribute] = value;
      }
    },
    [attribute, value]
  );

  useEffect(() => {
    if (element) setAttribute(element);
    if (elements && elements.length > 0) elements.forEach(setAttribute);
  }, [element, elements, setAttribute]);
};

export default useAttributes;