From bbd63400f94b43fde04449e0c71d14763d893e6a Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Thu, 19 May 2022 19:46:24 +0200
Subject: refactor: rewrite Prism hooks and providers

It avoid some hydratation errors on project pages (not in article
however) and the hooks are now reusable.
---
 src/utils/hooks/use-add-classname.tsx | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
 create mode 100644 src/utils/hooks/use-add-classname.tsx

(limited to 'src/utils/hooks/use-add-classname.tsx')

diff --git a/src/utils/hooks/use-add-classname.tsx b/src/utils/hooks/use-add-classname.tsx
new file mode 100644
index 0000000..0584084
--- /dev/null
+++ b/src/utils/hooks/use-add-classname.tsx
@@ -0,0 +1,34 @@
+import { useCallback, useEffect } from 'react';
+
+export type UseAddClassNameProps = {
+  className: string;
+  element?: HTMLElement;
+  elements?: NodeListOf<HTMLElement> | HTMLElement[];
+};
+
+/**
+ * Add className to the given element(s).
+ *
+ * @param {UseAddClassNameProps} props - An object with classnames and one or more elements.
+ */
+const useAddClassName = ({
+  className,
+  element,
+  elements,
+}: UseAddClassNameProps) => {
+  const classNames = className.split(' ').filter((string) => string !== '');
+
+  const setClassName = useCallback(
+    (el: HTMLElement) => {
+      el.classList.add(...classNames);
+    },
+    [classNames]
+  );
+
+  useEffect(() => {
+    if (element) setClassName(element);
+    if (elements && elements.length > 0) elements.forEach(setClassName);
+  }, [element, elements, setClassName]);
+};
+
+export default useAddClassName;
-- 
cgit v1.2.3

