summaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-attributes.tsx
blob: 97a7b438868ffe8701d32c90d0cfdc585b6ee5bf (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
import { useEffect } from 'react';

export type useAttributesProps = {
  /**
   * An HTML element.
   */
  element?: 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, attribute, value }: useAttributesProps) => {
  useEffect(() => {
    if (element) {
      element.dataset[attribute] = value;
    } else {
      document.documentElement.dataset[attribute] = value;
    }
  }, [attribute, element, value]);
};

export default useAttributes;