Skip to main content

Recipe: Adding a New CMS Component

This recipe guides you through the process of adding a new, custom component that can be rendered by the CMS, using the TextComponent from the shop template as a real-world example.

1. Create the React Component

First, create the React component itself. This is a standard React component that will receive its data as props. The CMSTextComponent simply renders HTML content.

// templates/shop/src/shop/client/features/cms/components/text/CMSTextComponent.tsx
import React from 'react';
import { RenderHTML } from 'react-native-render-html';

interface CMSTextComponentProps {
text: string;
}

function CMSTextComponent(props: CMSTextComponentProps) {
const { text } = props;
return <RenderHTML source={{ html: text }} />;
}

export default CMSTextComponent;

2. Define the Component Type Code

Add a new type code for your component in the CMSComponentTypeCode enum. This is used to identify the component type from the CMS data.

// templates/shop/src/shop/client/constants/cms.ts
export enum CMSComponentTypeCode {
// ... existing components
TEXT = 'CMSTextComponent',
}

3. Register the Component

Now, register your new component with the CMSComponentRegistry. This tells the application how to map the type code from the CMS to your React component.

// templates/shop/src/shop/client/features/cms/components/support/registry/CMSComponentRegistry.ts
import { CMSRegistry } from '@archibald/storefront';
import { CMSComponentTypeCode } from 'shop/client/constants';
import TextComponent from 'shop/client/features/cms/components/text';
// ... other component imports

const CMSComponentRegistry = new CMSRegistry();

// ... other component registrations
CMSComponentRegistry.register(CMSComponentTypeCode.TEXT, TextComponent);

export default CMSComponentRegistry;

Note: The TextComponent is imported from an index.ts file that dynamically loads the CMSTextComponent. This is a common pattern for code-splitting.

4. What to do in the CMS

  1. Create a new Component Type in your CMS (e.g., Contentful or SAP Commerce).
  2. The API name of this component type must match the CMSComponentTypeCode you defined (e.g., CMSTextComponent).
  3. Define the fields for your component type (e.g., a text field of type Rich Text).
  4. You can now add this component to your pages in the CMS, and it will be dynamically rendered in your Archibald application.