Skip to content

Commit c4d6add

Browse files
committed
add use meta tag hook
1 parent bf7ccce commit c4d6add

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/use-meta-tag.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { useEffect, useState } from 'react'
2+
/**
3+
* useTitle Hook to allow setting of the page title
4+
*
5+
* @param {string} key - The key to be used to set meta tag
6+
* @param {string} value - The value to be used in tag
7+
* @param {string} attribute - The attribute name to apply the key on the tag, defaults to name
8+
* @returns {[string, function]} - The title and setTitle function
9+
*/
10+
const useMetaTag = (key, value, attribute = 'name') => {
11+
const [metaValue, setMetaValue] = useState(value)
12+
useEffect(() => {
13+
const metaTag = document.querySelector(`meta[${attribute}="${key}"]`)
14+
if (!metaTag) {
15+
const meta = document.createElement('meta')
16+
meta.setAttribute(attribute, key)
17+
18+
meta.content = metaValue
19+
20+
document.getElementsByTagName('head')[0].appendChild(meta)
21+
} else {
22+
metaTag.setAttribute('content', metaValue)
23+
}
24+
}, [attribute, key, metaValue])
25+
26+
return [metaValue, setMetaValue]
27+
}
28+
29+
export default useMetaTag
30+
31+
export { useMetaTag }

0 commit comments

Comments
 (0)