i have this component for add Json LD schema to my pages.
Works great for urls like mysite.com/page or mysite.com/page/subpage... but, if i access to mysite.com/page/subpage/another-page, last schema thing is wrong : says mysite.com/subpage/another-page instead mysite.com/page/subpage/another-page
I know that problem is here const url = index === 0 ? `${baseURL}/${segment}` : `${baseURL}/${segments[index - 1]}/${segment}`; but i don't know how to make it works for segments higer than 2 levels. Could somebody help me please?
// Scripts
import { capitalizeEachWord } from "@/src/utils/utils";
import { scriptBodyUnencoded } from "@/src/components/functions/scriptFunctions";
const SCRIPT_BODY = dynamicSlug => {
const slug = dynamicSlug.substring(1);
const segments = slug.split("/");
const baseURL = `${process.env.CW_BASE_URL}`;
return `
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"item": {
"@type": "Thing",
"@id": "${baseURL}",
"name": "Home",
"image": ""
}
},
${segments.map((segment, index) => {
const url = index === 0 ? `${baseURL}/${segment}` : `${baseURL}/${segments[index - 1]}/${segment}`;
return `
{
"@type": "ListItem",
"position": ${index + 2},
"item": {
"@type": "Thing",
"@id": "${url}",
"name": "${capitalizeEachWord(segment.toLowerCase().replace(/-/g, " "))}",
"image": ""
}}`;
})}
]
}
`;
};
const JsonLdDynamicBreadcrumbComponent = ({
dynamicSlug,
}) => {
try {
return (
<script
dangerouslySetInnerHTML={{
__html: scriptBodyUnencoded(SCRIPT_BODY(dynamicSlug)),
}}
id="JsonLdDynamicBreadcrumbComponent"
type="application/ld+json"
/>
);
} catch (error) {
{/* eslint-disable-next-line react/jsx-no-useless-fragment -- need to return empty fragment*/ }
return <></>;
}
};
export default JsonLdDynamicBreadcrumbComponent;