rda-v3/client/src/lib/seo.ts
2025-12-21 20:51:37 +00:00

66 lines
2.2 KiB
TypeScript

import { useEffect } from "react";
const SITE_NAME = "Highland Group RDA";
const BASE_URL = "https://highlandgrouprda.org.uk";
const DEFAULT_DESCRIPTION =
"Highland Group RDA provides horse riding for people with disabilities in the Highlands, offering safe, fun, and therapeutic equestrian activities.";
const DEFAULT_IMAGE = "/Samantha-and-Connolly.jpg";
type PageMeta = {
title: string;
description?: string;
path?: string;
image?: string;
};
const setMeta = (attr: "name" | "property", key: string, value: string) => {
let tag = document.head.querySelector<HTMLMetaElement>(
`meta[${attr}="${key}"]`,
);
if (!tag) {
tag = document.createElement("meta");
tag.setAttribute(attr, key);
document.head.appendChild(tag);
}
tag.setAttribute("content", value);
};
const setCanonical = (href: string) => {
let link = document.head.querySelector<HTMLLinkElement>(
'link[rel="canonical"]',
);
if (!link) {
link = document.createElement("link");
link.setAttribute("rel", "canonical");
document.head.appendChild(link);
}
link.setAttribute("href", href);
};
export const usePageMeta = ({
title,
description = DEFAULT_DESCRIPTION,
path = "/",
image = DEFAULT_IMAGE,
}: PageMeta): void => {
useEffect(() => {
const pageTitle = `${SITE_NAME} - ${title}`;
const url = `${BASE_URL}${path === "/" ? "" : path}`;
const imageUrl = image.startsWith("http")
? image
: `${BASE_URL}${image}`;
document.title = pageTitle;
setMeta("name", "description", description);
setMeta("property", "og:title", pageTitle);
setMeta("property", "og:description", description);
setMeta("property", "og:type", "website");
setMeta("property", "og:url", url);
setMeta("property", "og:image", imageUrl);
setMeta("name", "twitter:card", "summary_large_image");
setMeta("name", "twitter:title", pageTitle);
setMeta("name", "twitter:description", description);
setMeta("name", "twitter:image", imageUrl);
setCanonical(url);
}, [title, description, path, image]);
};