1. Getting started with SitecoreAI

Build your first component

This is part four of the getting started walkthrough series. Before you can complete the steps here, make sure you have created a project and environment, created a site and page, and set up your local development environment.

In this example, you'll be adding a code component that includes a title and text. To create the component, you will clone one of the existing components that are included out of the box in SitecoreAI. Cloning an existing component saves development time by creating the boilerplate items and configurations that your component requires, and makes sure that the required base templates are configured to support the content authoring features in the Page builder.

This walkthrough describes how to:

  1. Create and deploy the new component
  2. Create the rendering definition
  3. Add the component to your site page

Create and deploy the new component

In the first step, you create the component structure in your local project.

Content SDK (Next.js)

If you're using Content SDK, you create a React component. The component accepts the following properties:

  • rendering – contains information about the component's presentation (rendering).
  • params – an object containing parameters passed to the component from Sitecore.

The component uses the following Sitecore parameters:

ParameterDescription
StylesCSS classes for the container.
GridParametersCSS classes for the grid system (for example, Bootstrap).
RenderingIdentifierA unique identifier for the component, used for analytics.

In addition, if you create a component that includes styles that can be configured in the right-hand side in Pages, you can use the data-class-change attribute in the relevant HTML element. In Pages, when the content author changes styles in the styling menu, those changes will be reflected in the preview canvas.

To create the new component:

  1. Ensure you still have the cloned repository open in your code editor.

  2. In the /examples/kit-nextjs-skate-park/src/components folder, create a new file and name it TitleAndText.tsx.

  3. Paste the following code into the new file:

    tsx
    import React from 'react';
    import { Field, Text } from '@sitecore-content-sdk/nextjs';
    
    interface Fields {
      Title: Field<string>;
      Text: Field<string>;
    }
    
    type TitleAndTextProps = {
      params: { [key: string]: string };
      fields: Fields;
    };
    
    export const Default = (props: TitleAndTextProps): React.ReactElement => {
      const containerStyles = props.params && props.params.styles ? props.params.styles : '';
      const styles = \`${props.params.GridParameters} ${containerStyles}\`.trimEnd();
    
      return (
        <div className={\`container-default component ${styles}\`}>
          <div data-class-change className={containerStyles}>
            This container must be refreshed without reloading the page.
          </div>
          <h1 className="component-content title row">
            <Text field={props.fields.Title} />
          </h1>
          <div className="component-content text row">
            <Text field={props.fields.Text} />
          </div>
        </div>
      );
    };
  4. Save the file.

    Important

    Ensure the file ends on a single new line or it will not compile.

  5. Add the change to a commit and push the change to your repo. This will automatically kick off a deployment to SitecoreAI. You can follow its progress in the Deploy app. Proceed to the next step after the deployment is complete.

ASP.NET Core SDK

If you're using the ASP.NET Core SDK, you create a C# component. The component uses the following Sitecore parameters:

ParameterDescription
StylesCSS classes for the container.
GridParametersCSS classes for the grid system (for example, Bootstrap).
RenderingIdentifierA unique identifier for the component, used for analytics.

In addition, if you create a component that includes styles that can be configured in the right-hand side in Pages, you can use the data-class-change attribute in the relevant HTML element. In Pages, when the content author changes styles in the styling menu, those changes will be reflected in the preview canvas.

To create a new component:

  1. Return to the Sites dashboard, where you created your site earlier. Click the Options actions.png menu, and click Edit in Page builder to open Pages. You will initially see an error, because you need to connect Pages to your local running developer instance.

  2. Click the Default editing host menu and select Local host.

  3. Enter the value to connect to your locally running instance, https://localhost:5001, and save. Pages is now connected to your local development environment, and displays three empty placeholders.

    Pages connected to your local host to get started with ASP.NET
  4. In the left-hand pane, click Components components.png, locate the Title component, and drag it onto the plus sign in the middle of your page.

  5. The initial page title is shown in the canvas. On the right, on the Content tab, click Open Page content to edit the field value.

  6. Ensure you still have the cloned repository open in your code editor.

  7. In the /headapps/aspnet-core-starter/models folder, create a new file called TitleAndText.cs.

  8. Paste the following code into the new file:

    csharp
    using Sitecore.AspNetCore.SDK.LayoutService.Client.Response.Model.Fields;
    using Sitecore.AspNetCore.SDK.RenderingEngine.Binding.Attributes;
    
    namespace Sitecore.AspNetCore.Starter.Models;
    public class TitleAndText
    {
        [SitecoreComponentField]
        public TextField? Title { get; set; }
    
        [SitecoreComponentField]
        public TextField? Text { get; set; }
    }
  9. In the /headapps/aspnet-core-starter/Views/Shared/Components/SitecoreComponent folder, create a new file called TitleAndText.cshtml.

  10. Paste the following code into the new file:

    html
    @model TitleAndText
    
    <div class="container-default">
    	<h1 class="component title row">
    		<sc-text asp-for="@Model.Title" />
    	</h1>
    	<div class="component text row">
    		<sc-text asp-for="@Model.Text" />
    	</div>
    </div>
  11. Open the /headapps/aspnet-core-starter/Extensions/ServiceCollectionExtensions.cs file, and add a call to the AddModelBoundView method to register your new component and its model. The class should now look like this (note the extra line registering the TitleAndText component that you added):

    csharp
    using Sitecore.AspNetCore.SDK.RenderingEngine.Configuration;
    using Sitecore.AspNetCore.Starter.Models.LinkList;
    using Sitecore.AspNetCore.Starter.Models.Navigation;
    using Sitecore.AspNetCore.Starter.Models.Title;
    
    namespace Sitecore.AspNetCore.Starter.Extensions;
    
    public static class ServiceCollectionExtensions
    {
    	public static RenderingEngineOptions AddStarterKitViews(this RenderingEngineOptions renderingEngineOptions)
    	{
    		renderingEngineOptions.AddModelBoundView<Title>("Title")
    			.AddModelBoundView<Container>("Container")
    			.AddModelBoundView<ColumnSplitter>("ColumnSplitter")
    			.AddModelBoundView<RowSplitter>("RowSplitter")
    			.AddModelBoundView<PageContent>("PageContent")
    			.AddModelBoundView<RichText>("RichText")
    			.AddModelBoundView<Promo>("Promo")
    			.AddModelBoundView<LinkList>("LinkList")
    			.AddModelBoundView<Image>("Image")
    			.AddModelBoundView<PartialDesignDynamicPlaceholder>("PartialDesignDynamicPlaceholder")
    			.AddModelBoundView<Navigation>("Navigation")
    			.AddModelBoundView<TitleAndText>("TitleAndText");
    
    		return renderingEngineOptions;
    	}
    }
  12. Add the change to a commit and push the change to your repo. This will automatically kick off a deployment to SitecoreAI. You can follow its progress in the Deploy app. Proceed to the next step after the deployment is complete.

Create the rendering definition

Now you can create the rendering definition for the component. Rendering definitions are used to tell SitecoreAI where in the project the component's .tsx file is, and what data it needs to render correctly. You'll do this by cloning an existing rendering, thereby automatically generating all the required items, instead of having to do it manually. Then, you'll add the rendering to the headless module that was created when you created the site collection. You can find the module in /sitecore/system/Settings/Project.

To clone the component:

  1. In the Cloud Portal, click the tile for the environment you created earlier, for example, Getting Started.

  2. In the pane on the right, click Open app.

  3. On the top menu bar, click Content, then click Content Editor.

  4. In the Content Editor, navigate to /sitecore/layout/Renderings/Feature/Headless Experience Accelerator/Page Content/Rich Text. On the Content tab, scroll down to the Customize Page section and, to ensure the component is visible in Pages, make sure the Editable check box is selected.

    Rich Text component window showing checked editable check box
  5. Right-click the rendering named Rich Text and click Scripts > Clone Rendering.

  6. In the Create derivative rendering window, specify the following:

    • On the General tab, enter the name TitleAndText.
    • On the General tab, in the Add to module field, select Renderings/Project/Getting Started/Getting Started Content.
    • On the Parameters tab, select Make a copy of original rendering parameters. This decouples the rendering from the original component and reduces dependencies.
    • On the Datasource tab, in the Datasource field, select Make a copy of original datasource.
    The Create derivative rendering window used when cloning the Rich Text rendering in the Content Editor
  7. Click Proceed, and close the window when the process is finished.

  8. Navigate to /sitecore/templates/Project/Getting Started/Getting Started Content/Text, and on the Builder tab, change the values for the fields you created:

    • Title - select Single-Line Text.
    • Text - select Multi-Line Text.
    Defining the fields in the new title and text component in the Content Editor
  9. Make sure the Source column is empty for both fields.

  10. In the upper-left corner, click Save.

    Save icon in Content Editor
  11. Navigate to /sitecore/content/Getting Started/Getting Started/Presentation/Available Renderings.

  12. Right-click the Available Renderings item and click Insert > Available Renderings.

  13. Name the new item Getting Started Content and click OK. The new item opens automatically.

  14. In the Renderings field, click Edit.

  15. In the tree on the left, locate and select the rendering item you created previously at /Layout/Renderings/Project/Getting Started/Getting Started Content/TitleAndText. Click the arrow to move it to the list on the right, then click OK.

    Edit the rendering to include the new title and text component
  16. In the upper-left corner, click Save.

  17. To navigate back to the main SitecoreAI dashboard, click the Launchpad XMC_Switcher.png.

Add the component to your site page

At this stage, you've completed the required configuration for the new component and it's available to use on your site. In this step, you can return to Pages and add the component to the page you created earlier, after which you'll be able to see it on your local development instance.

To add the component to your site page:

  1. On the main Channels dashboard, hover over the new site tile, click Page builder. Alternatively, in a new browser tab, open https://pages.sitecorecloud.io/.
  2. On the Components tab, in the Getting Started Content section, you can now see the TitleAndText component. Drag it onto one of the plus icons on the page. You should now see the component rendered on the page, with a No text in field indicator for the title and text fields.
  3. Enter some text for the title and text fields.
  4. In your browser, navigate to your local host to see the new component rendered with the text you entered (for Content SDK, this is http://localhost:3000/ ; for .NET, this is http://localhost/5001/).

You've completed the walkthrough series! You can now continue to create new components, test your changes locally, and push to your source control provider - this kicks off a deployment in SitecoreAI and makes new components available in the Page builder.

If you have suggestions for improving this article, let us know!