portfolio-page/src/hooks/usePageSeo.ts

64 lines
1.7 KiB
TypeScript

import { useEffect } from 'react';
interface SeoProps {
title: string;
description: string;
canonical?: string;
noIndex?: boolean;
image?: string;
}
const BASE_URL = 'https://sascha-bach.de';
export function usePageSeo({ title, description, canonical, noIndex, image }: SeoProps) {
useEffect(() => {
document.title = title;
const setMeta = (name: string, content: string, isProperty = false) => {
const attr = isProperty ? 'property' : 'name';
let el = document.querySelector<HTMLMetaElement>(`meta[${attr}="${name}"]`);
if (!el) {
el = document.createElement('meta');
el.setAttribute(attr, name);
document.head.appendChild(el);
}
el.content = content;
};
setMeta('description', description);
setMeta('og:title', title, true);
setMeta('og:description', description, true);
setMeta('twitter:title', title);
setMeta('twitter:description', description);
if (image) {
const imageUrl = image.startsWith('http') ? image : `${BASE_URL}${image}`;
setMeta('og:image', imageUrl, true);
setMeta('twitter:image', imageUrl);
}
if (canonical) {
setMeta('og:url', `${BASE_URL}${canonical}`, true);
let link = document.querySelector<HTMLLinkElement>('link[rel="canonical"]');
if (!link) {
link = document.createElement('link');
link.rel = 'canonical';
document.head.appendChild(link);
}
link.href = `${BASE_URL}${canonical}`;
}
if (noIndex) {
setMeta('robots', 'noindex, nofollow');
}
return () => {
if (noIndex) {
const robotsMeta = document.querySelector('meta[name="robots"]');
robotsMeta?.remove();
}
};
}, [title, description, canonical, noIndex]);
}