Tailwind Logo

Implement multilingual support with the created components

XM Cloud

Published: 2024-03-07

The breadcrumb list component we created in the last issue, how will it behave when it is multilingual? This time, we will update the component with that part in mind.

Verify operation in Japanese

For the previous code, we will check to see if we can get the language from sitecoreContext in the processing part when there is data.

TypeScript
  if (data) {
    return (
      <>
        <div className="component-content">{generateBreadcrumbList(data.item.ancestors)}</div>
        <div>id: {sitecoreContext.language}</div>
      </>
    );
  }

The results of aligning Japanese resources are displayed as follows.

headlessmultilang01.png

Update components

The added code is able to check the language, but the URL is generated based on the data returned by GraphQL, so the path does not contain ja-JP. If not, update the component to add the locale.

First, add code to the calling function to adjust the URL using locale.

TypeScript
function generateBreadcrumbList(ancestors: Ancestor[], locale: string): JSX.Element {
  const reversedAncestors = ancestors.reverse();

  const baseUrl = locale === 'en' ? '' : `/${locale}`;

  const ancestorListItems = reversedAncestors.map((ancestor: Ancestor, index: number) => {
    return (
      <li key={index}>
        <a href={baseUrl + ancestor.url.path}>{ancestor.field.value}</a>
      </li>
    );
  });

This will do nothing for "en". When "ja-jp" is used, /ja-JP will be added.

Then pass the language that will be the locale in the part of the code that is making the call.

TypeScript
  const { sitecoreContext } = useSitecoreContext();
  const locale = sitecoreContext.language || 'en';

  if (data) {
    return (
      <>
        <div className="component-content">
          {generateBreadcrumbList(data.item.ancestors, locale)}
        </div>
      </>
    );
  }

Now you can add the locale to the URL when generating HTML. Execution.

headlessmultilang02.png

Summary

When creating a component, the GraphQL side used $language to get the data for that language, and the component side got the language from sitecoreContext.language, which allowed for URL-related adjustments.

Tags