-
Notifications
You must be signed in to change notification settings - Fork 0
/
headtags.js
39 lines (34 loc) · 1.02 KB
/
headtags.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useEffect } from "react";
function HeadTags({ title, description, keywords, context }) {
useEffect(() => {
// Update the document title
if (typeof document !== "undefined") {
document.title = title;
// Update or create meta tags
updateMetaTag("title", title);
updateMetaTag("description", description);
updateMetaTag("keywords", keywords);
}
}, [title, description, keywords]);
// If running in SSR, update the context
if (context) {
context.title = title;
context.description = description;
context.keywords = keywords;
}
}
// Helper function to update or create meta tags
function updateMetaTag(name, content) {
if (content) {
let tag = document.querySelector(`meta[name="${name}"]`);
if (tag) {
tag.setAttribute("content", content);
} else {
tag = document.createElement("meta");
tag.setAttribute("name", name);
tag.setAttribute("content", content);
document.head.appendChild(tag);
}
}
}
export default HeadTags;