Files
bayarea/components/SEO.tsx
2026-03-25 20:07:27 -05:00

92 lines
3.1 KiB
TypeScript

import React, { useEffect } from 'react';
interface SEOProps {
title: string;
description: string;
keywords?: string[];
canonicalUrl?: string;
schema?: object; // JSON-LD schema
ogImage?: string;
ogType?: string;
}
const SEO: React.FC<SEOProps> = ({ title, description, keywords, canonicalUrl, schema, ogImage, ogType }) => {
useEffect(() => {
// Update Title
document.title = title;
// Helper to set meta tag (name attribute)
const setMetaTag = (name: string, content: string) => {
let element = document.querySelector(`meta[name="${name}"]`);
if (!element) {
element = document.createElement('meta');
element.setAttribute('name', name);
document.head.appendChild(element);
}
element.setAttribute('content', content);
};
// Helper to set OG tag (property attribute)
const setOgTag = (property: string, content: string) => {
let element = document.querySelector(`meta[property="${property}"]`);
if (!element) {
element = document.createElement('meta');
element.setAttribute('property', property);
document.head.appendChild(element);
}
element.setAttribute('content', content);
};
// Update Meta Description
setMetaTag('description', description);
// Update Keywords
if (keywords && keywords.length > 0) {
setMetaTag('keywords', keywords.join(', '));
}
// Update Canonical
if (canonicalUrl) {
let link = document.querySelector('link[rel="canonical"]');
if (!link) {
link = document.createElement('link');
link.setAttribute('rel', 'canonical');
document.head.appendChild(link);
}
link.setAttribute('href', canonicalUrl);
}
// Open Graph Tags
setOgTag('og:title', title);
setOgTag('og:description', description);
setOgTag('og:type', ogType || 'website');
setOgTag('og:site_name', 'Bay Area IT');
if (canonicalUrl) setOgTag('og:url', canonicalUrl);
if (ogImage) setOgTag('og:image', ogImage);
// Twitter Card Tags
setMetaTag('twitter:card', 'summary');
setMetaTag('twitter:title', title);
setMetaTag('twitter:description', description);
// Inject Schema
if (schema) {
const scriptId = 'seo-schema-script';
let script = document.getElementById(scriptId);
if (!script) {
script = document.createElement('script');
script.id = scriptId;
script.setAttribute('type', 'application/ld+json');
document.head.appendChild(script);
}
script.textContent = JSON.stringify(schema);
}
}, [title, description, keywords, canonicalUrl, schema, ogImage, ogType]);
return null;
};
export default SEO;