aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-attributes.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks/use-attributes.tsx')
-rw-r--r--src/utils/hooks/use-attributes.tsx52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/utils/hooks/use-attributes.tsx b/src/utils/hooks/use-attributes.tsx
new file mode 100644
index 0000000..6d18048
--- /dev/null
+++ b/src/utils/hooks/use-attributes.tsx
@@ -0,0 +1,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;