diff options
Diffstat (limited to 'src/utils/hooks/use-attributes.tsx')
| -rw-r--r-- | src/utils/hooks/use-attributes.tsx | 33 |
1 files changed, 33 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..97a7b43 --- /dev/null +++ b/src/utils/hooks/use-attributes.tsx @@ -0,0 +1,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; |
