File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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 }
You can’t perform that action at this time.
0 commit comments