0

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;

1 Answer 1

0

while iterating, try joining all segments until the current by its index:

try:

${segments.map((segment, index) => {
    const url = `${baseURL}/${segments.slice(0, index+1).join('/')}`;
    //..
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.