aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-attributes.tsx
blob: 20e9947ddbb7b0bcd6865eea2e8e9046740cf33c (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
import { useCallback, useEffect } from 'react';
import { fromKebabCaseToCamelCase } from '../helpers';

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.
 */
export 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]);
};