aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-attributes.tsx
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-05-19 19:46:24 +0200
committerArmand Philippot <git@armandphilippot.com>2022-05-19 19:46:24 +0200
commitbbd63400f94b43fde04449e0c71d14763d893e6a (patch)
tree057055dce19fc71c7c2e2fa05b691144224dfbd0 /src/utils/hooks/use-attributes.tsx
parent806004ab79ac4e1cb49cef93ab3f35a08c5c82b5 (diff)
refactor: rewrite Prism hooks and providers
It avoid some hydratation errors on project pages (not in article however) and the hooks are now reusable.
Diffstat (limited to 'src/utils/hooks/use-attributes.tsx')
-rw-r--r--src/utils/hooks/use-attributes.tsx35
1 files changed, 27 insertions, 8 deletions
diff --git a/src/utils/hooks/use-attributes.tsx b/src/utils/hooks/use-attributes.tsx
index 97a7b43..6d18048 100644
--- a/src/utils/hooks/use-attributes.tsx
+++ b/src/utils/hooks/use-attributes.tsx
@@ -1,4 +1,5 @@
-import { useEffect } from 'react';
+import { fromKebabCaseToCamelCase } from '@utils/helpers/strings';
+import { useCallback, useEffect } from 'react';
export type useAttributesProps = {
/**
@@ -6,6 +7,10 @@ export type useAttributesProps = {
*/
element?: HTMLElement;
/**
+ * A node list of HTML Element.
+ */
+ elements?: NodeListOf<HTMLElement> | HTMLElement[];
+ /**
* The attribute name.
*/
attribute: string;
@@ -20,14 +25,28 @@ export type useAttributesProps = {
*
* @param props - An object with element, attribute name and value.
*/
-const useAttributes = ({ element, attribute, value }: useAttributesProps) => {
+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) {
- element.dataset[attribute] = value;
- } else {
- document.documentElement.dataset[attribute] = value;
- }
- }, [attribute, element, value]);
+ if (element) setAttribute(element);
+ if (elements && elements.length > 0) elements.forEach(setAttribute);
+ }, [element, elements, setAttribute]);
};
export default useAttributes;