Was this page helpful?

Register custom components

To use custom components in Experiences, you need to register them.

To register custom components:

  1. Import the component.

Import the component from the source package or file.

In our example, we import the Button component from the custom component example.

import { Button } from './components/Button';
  1. Write the component definition.

A component definition is a JSON object that Contentful uses to pass necessary properties to the component.

In our example, we define variables for text and variant because these are props on the Button component in the custom component example.

Setting up these variables in the component definition enables content and design inputs in the Experiences UI:

  • The text property enables content binding for the button's text.
  • The variant property provides a select input in the design sidebar, allowing editors to choose the button's style.

To learn more about the component definitions and what features they provide, please refer to the component definition.

// src/components/buttonDefinition.ts

export const buttonDefinition = {
  id: 'custom-button',
  name: 'Button',
  category: 'Custom Components',
  variables: {
    text: {
      displayName: 'Text',
      type: 'Text',
      defaultValue: 'Click me',
    },
    variant: {
      displayName: 'Variant',
      type: 'Text',
      defaultValue: 'primary',
      group: 'style',
      validations: {
        in: [
          { value: 'primary', displayName: 'Primary', },
          { value: 'secondary', displayName: 'Secondary', },
        ],
      },
    },
  },
};
  1. Register the component.

Import the defineComponents function from the Experiences SDK and call it with your component definitions.

// src/registeredComponents.ts

import { defineComponents } from '@contentful/experiences-sdk-react';
import { Button } from './components/Button';
import { buttonDefinition } from './components/buttonDefinition';

defineComponents([
  {
    component: Button,
    definition: buttonDefinition,
  },

  // Register additional components below...
  // {
  //   component: Example,
  //   definition: exampleDefinition,
  // }
]);
Important: The source code of each registered custom component stays in your application and nothing besides the component definition (a JSON object) is sent to Contentful over postMessage. Any change made to the component source code has immediate effect on its representation in the Experiences.