Tailwind Logo

Create components using the code generated by ChatGPT as a reference

XM CloudHeadless SXA

Published: 2023-10-18

ChatGPT, which is breaking out this year as a generative AI, presents us with JavaScript and TypeScript samples. In this article, we would like to use the code generated by ChatGPT to create a component for XM Cloud.

Creating YouTube Components

The first step is to create a component for YouTube, but first create a simple component. The procedure is described in a separate article on how to use the wizard.

In this case, the component name was created as YouTube and Multimedia/32x32/video_camera.png was used for the icon. The icon is displayed as follows.

xmcchatgpt01.png

Contact ChatGPT

I will consult ChatGPT for the code as soon as possible.

How to write a typescript component sample that embeds a YouTube video

They will respond with the code as follows.

xmcchatgpt01.png

The actual code provided is shown below in this case.

TypeScript
import React, { useRef, useEffect } from 'react';

interface YouTubeEmbedProps {
  videoId: string;
  width?: number;
  height?: number;
}

const YouTubeEmbed: React.FC<YouTubeEmbedProps> = ({ videoId, width = 560, height = 315 }) => {
  const playerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (playerRef.current) {
      const iframe = document.createElement('iframe');
      iframe.src = `https://www.youtube.com/embed/${videoId}`;
      iframe.width = width.toString();
      iframe.height = height.toString();
      iframe.frameBorder = '0';
      iframe.allowFullscreen = true;
      playerRef.current.appendChild(iframe);
    }
  }, [videoId, width, height]);

  return (
    <div ref={playerRef}></div>
  );
};

export default YouTubeEmbed;

Let's use this code as a guide to create Headless SXA components.

Defining Item Fields

In the above code, there are three items regarding the properties used by the component: videoId, width and height. Therefore, we will change the items in the pre-prepared component template.

xmcchatgpt03.png

Also, set the Standard Value, this time with the size as the default.

xmcchatgpt04.png

The YouTube.tsx file was changed accordingly as follows

TypeScript
import React from 'react';
import { Field, Text } from '@sitecore-jss/sitecore-jss-nextjs';

interface Fields {
  videoId: Field<string>;
  width: Field<string>;
  height: Field<string>;
}

type YouTubeProps = {
  params: { [key: string]: string };
  fields: Fields;
};

export const Default = (props: YouTubeProps): JSX.Element => {
  return (
    <div className={`component myrendering ${props.params.styles}`}>
      <div className="component-content">
        <div>
          <strong>テスト:</strong>
          <Text field={props.fields.videoId} />
          <div>width={props.fields.width.value}</div>
          <div>height={props.fields.height.value}</div>
        </div>
      </div>
    </div>
  );
};

If you actually place this component on your page, it will look like this This time, we enter the YouTube ID and save it. As a result, we have a YouTube item as an item associated with Home.

xmcchatgpt06.png

Merging Codes

This time, we are going to go a bit wild and copy and paste the code provided by ChatGPT for the YouTube.tsx file.

xmcchatgpt07.png

The following changes were made

  • import : Because of the duplication, one line is listed at the top of the list, as described by ChatGPT.
  • interface : part is also moved up
  • YouTubeEmbedProps : I used to include width? and height? in the definition, but I want to be sure to pass values, so I removed the ? in the definition.
  • In addition, change number to string this time because the data received from Sitecore will be used as text.

As a result, we started with the following code.

TypeScript
import React, { useRef, useEffect } from 'react';
import { Field, Text } from '@sitecore-jss/sitecore-jss-nextjs';

interface Fields {
  videoId: Field<string>;
  width: Field<string>;
  height: Field<string>;
}

interface YouTubeEmbedProps {
  videoId: string;
  width: string;
  height: string;
}

type YouTubeProps = {
  params: { [key: string]: string };
  fields: Fields;
};

Next, rewrite the part of the function that displays the YouTube feed obtained from ChatGPT as a function. The changes are,

  • Remove standard values for width and height
  • Remove Visual Studio Code's warning about iframe.frameBorder.
  • Remove .toString() for width and height, as they are taken as strings from Sitecore.

The result is as follows

TypeScript
function YouTubeEmbed({ videoId, width, height }: YouTubeEmbedProps) {
  const playerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (playerRef.current) {
      const iframe = document.createElement('iframe');
      iframe.src = `https://www.youtube.com/embed/${videoId}`;
      iframe.width = width;
      iframe.height = height;
      iframe.allowFullscreen = true;
      playerRef.current.appendChild(iframe);
    }
  }, [videoId, width, height]);

  return <div ref={playerRef}></div>;
}

This function is configured to be called by Default. The call is simple and looks like this

TypeScript
export const Default = (props: YouTubeProps): JSX.Element => {
  return (
    <div className={`component myrendering ${props.params.styles}`}>
      <div className="component-content">
        <div>
          <YouTubeEmbed
            videoId={props.fields.videoId.value}
            width={props.fields.width.value}
            height={props.fields.height.value}
          />
        </div>
      </div>
    </div>
  );
};

Now we can incorporate the code generated by ChatGPT as a function and refer to the Sitecore value.

Operation check and debugging

The following is an actual page with pre-created components in place.

xmcchatgpt08.png

Two YouTube videos are lined up. Ask ChatGPT about this debugging as well.

xmcchatgpt09.png

The answer was returned.

xmcchatgpt10.png

The difference in the code is the comment section that appears on the screen. After actually reflecting this, the component is displayed as follows.

xmcchatgpt11.png

The component for embedding YouTube videos worked successfully.

Finally, we will reorganize the code. This is because there are still some imports that have been merged or are no longer used.

TypeScript
import React, { useRef, useEffect } from 'react';
import { Field } from '@sitecore-jss/sitecore-jss-nextjs';

The build is now complete and the component has been successfully completed.

Summary

In the last issue, we showed you how to create a component using the wizard. In that case, we defined only text fields. This time, we created a sample using ChatGPT to prepare the code to display a YouTube video. Also, that sample itself ended up displaying two videos, but we were able to debug how to make it into one using ChatGPT.

ChatGPT is definitely the master when it comes to Typescript. It's a good time to be able to create components like this that can be managed by Sitecore.

Tags