blob: 6d180489c8326a18ab1fece206348623bd15904e (
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 { fromKebabCaseToCamelCase } from '@utils/helpers/strings';
import { useCallback, useEffect } from 'react';
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;
|