Skip to content

Creating a component ​

Components live in your subtheme (see Base theme and subthemes). The base theme only provides the React runtime and helpers that frame/react attaches. Below, my_theme stands for your subtheme.

Each widget lives in its own folder under components/. Drupal discovers it because it contains <name>.component.yml (theme components are namespaced by the theme machine name: my_theme:pricing-table).

components/
  pricing-table/
    pricing-table.component.yml           # SDC metadata: props, slots, library
    pricing-table.twig                    # server markup: the mount point
    index.jsx                             # entry: Drupal behavior that mounts React
    PricingTable.jsx                      # the React component
    pricing-table.scss                    # imported from index.jsx
    pricing-table.story.twig              # optional, for Storybook
    __tests__/pricing-table.test.js       # optional, jest

The examples below are cut down from the pricing-table component of the example subtheme (examples/frame_demo_umami).

The three files that make a component ​

*.component.yml ​

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: Pricing table
status: stable
group: Marketing
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
    currency:
      type: string
      title: Currency
    plans:
      type: array
      title: Plans
      items:
        type: object
        properties:
          name: { type: string }
          monthly: { type: number }
        required: [name, monthly]
  required:
    - plans
libraryOverrides:
  js:
    ../../assets/pricing-table.js: { attributes: { type: module } }
  css:
    theme:
      ../../assets/pricing-table.css: { }
  dependencies:
    - frame/react
  • props are validated by core when the component renders. Wrong type or a missing required prop is an error, which is what you want while developing.
  • libraryOverrides is the SDC way to attach assets. Core builds a library for the component and attaches it only on pages where the component renders. Paths are relative to the component folder, and the Vite output lives in the theme's assets/, hence ../../assets/. (Core turns them into /core/../themes/... URLs, which browsers normalize, this is core behavior.)
  • dependencies pull the global React libraries in before your entry runs. Add frame/react-api-client too if the component calls apiClient.
  • Because the Vite output is ES modules (shared chunks), the script needs attributes: { type: module }. See Build.

Convention alternative

SDC also auto-attaches pricing-table.js and pricing-table.css found next to the twig file. That works if your build writes there. This scaffold writes everything to assets/ (one place to git-ignore and deploy), so it uses libraryOverrides.

*.twig: the mount point ​

twig
{% set data = { heading: heading, currency: currency|default(''), plans: plans } %}
<section {{ attributes.addClass('pricing-table').setAttribute('data-props', data|json_encode) }}>
  <h2>{{ heading }}</h2>
  <ul>
    {% for plan in plans %}
      <li>{{ plan.name }}: {{ plan.monthly }}</li>
    {% endfor %}
  </ul>
</section>

Twig renders the markup that a visitor without JavaScript and a search engine read (the real component prints the plans in full), and passes the props to React in one JSON attribute, data-props. attributes is provided by SDC, so callers can add classes and attributes. For a few plain values you can use separate data-* attributes instead (.setAttribute('data-limit', limit)) and read them from element.dataset.

index.jsx: the Drupal behavior ​

jsx
import { createRoot } from 'react-dom/client';
import { PricingTable } from './PricingTable';
import './pricing-table.scss';

(function (Drupal, once) {
  const mount = (element) => {
    createRoot(element).render(<PricingTable {...JSON.parse(element.dataset.props || '{}')} />);
  };

  Drupal.behaviors.frameDemoPricingTable = {
    attach(context) {
      once('react', '.pricing-table', context)
        .forEach((element) => executeWhenVisible(element, mount, 'pricing-table'));
    },
  };
})(Drupal, once);

Keep index.jsx thin: it only wires Drupal to React. Why it is written like this is explained in React + Drupal behaviors.

Add a new component, step by step ​

  1. Folder: components/my-widget/.
  2. my-widget.component.yml: name, props, libraryOverrides pointing to ../../assets/my-widget.js and .css (the file names come from the folder name, see below), dependency on frame/react.
  3. my-widget.twig: the mount element with a class and data-* props.
  4. index.jsx: copy the behavior above, change the selector, behavior name and the component.
  5. MyWidget.jsx and my-widget.scss.
  6. npm run build. The Vite config scans components/*/index.jsx and names the bundle after the folder, so my-widget/ produces assets/my-widget.js and assets/my-widget.css.
  7. drush cr, then place it in Twig.

The folder name is also the bundle name, so keep the three in sync: folder my-widget, bundle assets/my-widget.js, and the path in libraryOverrides.

Props or slots? ​

SDC gives you two ways to pass content in. Choose by what the value is:

Use a prop whenUse a slot when
it is a value: string, number, boolean, enum, URL, IDit is content: markup, links, a render array, translated rich text
you want core to validate it (type, enum, required, default)the caller may want to put any HTML or other components inside
React needs it as data (currency, variant, limit)Drupal should render it (page title, field output, a block)
it is small and safe in an HTML attributeit could contain user content you do not want to double-encode

Rules of thumb:

  • Config for React → props. currency, variant, heading. They end up in data-* attributes and element.dataset.
  • Anything Drupal renders → slots. Never pass rendered HTML as a prop string, it is escaped and bypasses Drupal's render pipeline.
  • Enums over free text for anything that changes behavior (variant: light | dark), the schema documents and enforces them.
  • Optional props need |default() in twig. The default: in component.yml documents the value, but core SDC does not apply it to the Twig variables: an omitted prop is simply undefined, and data-start="{{ start }}" becomes an empty attribute (Number(undefined) is NaN in JS). Write start|default(0) in the template and, for numbers, Number(el.dataset.start) || 0 in index.jsx. Keep the same default in component.yml so the documentation matches.
  • Prop values are strings in the browser. data-limit="10" arrives as "10". Parse numbers and booleans in index.jsx, or send structured data as one JSON attribute and JSON.parse it.
  • Slot content is server markup. React replaces the element's children when it mounts, so read what you need first (element.innerText, element.innerHTML) and render it yourself. Better still, keep slot content out of the React root: a component with slots, like Tabs, is plain Twig and CSS, with a small script (tabs.js) that only adds behavior to the server markup.

Slot example (tabs) ​

yaml
# tabs.component.yml
props:
  type: object
  properties:
    label: { type: string, title: 'Name for screen readers' }
    vertical: { type: boolean, title: 'Tabs on the side' }
slots:
  tabs:
    title: Tabs
    description: 'Tab blocks, one per tab.'
twig
<div {{ attributes.addClass('tabset').setAttribute('data-tabset-label', label) }}>
  <div class="tabset__panels">{% block tabs %}{% endblock %}</div>
</div>

label and vertical are values, tabs is whatever Drupal wants shown inside: in the editor, the Tab components dropped into it. The tab component has a slot of its own (content), so tabs nest slots two levels deep.

Gotchas and advice ​

Naming and wiring

  • The folder name is the bundle name: folder my-widget → assets/my-widget.js/.css. The path in libraryOverrides, the folder and the component ID (my_theme:my-widget) must agree. A typo gives a 404 for the script, not an error.
  • index.jsx is required for the build to pick the folder up (index.js also works). Other files are free.
  • One behavior per component, named uniquely (Drupal.behaviors.myWidget). A clashing name silently replaces another behavior.
  • Use a specific mount class (.my-widget) in once(). A generic selector mounts React into unrelated markup.
  • The once() id ('react') can be shared: once tracks element and id together, different elements never conflict.

Libraries

  • Always depend on frame/react (and frame/react-api-client if you call apiClient). Without it React, apiClient and executeWhenVisible are undefined and the component fails silently.
  • If the HTML you render contains ajax links or dropbuttons, add core/drupal.ajax / core/drupal.dropbutton, see Ajax. These pull jQuery in through core, your code does not need it.
  • Scripts that are ES modules need attributes: { type: module }, see Build.

JavaScript

  • import './my-widget.scss' in index.jsx. Vite extracts the CSS into assets/my-widget.css. Third-party CSS (for example some-library/dist/style.css) must be imported the same way, it is not automatic.
  • Use Drupal.t() / Drupal.formatPlural() for text. Drupal, once and drupalSettings are globals, do not bundle them.
  • React is an external, so it is not bundled: import { useState } from 'react' is fine, it resolves to the global React. Do not add a second React to a component's dependencies.
  • Keep React component files free of Drupal globals where you can. Pass the data and the text in as props, so Jest tests do not need Drupal.
  • Handle loading, error and empty states. The server markup is a bare mount element, users see it until your first render.

Markup and accessibility

  • Put server-rendered fallback inside the mount element (<noscript>, or real content that React replaces). It is what search engines and no-JS users get.
  • Prefer real form controls, labels and aria-live for results. React does not add them for you.
  • SDC attributes lets callers add classes and attributes, keep attributes.addClass(...) in twig instead of hardcoding a bare <div>.

Workflow

  • After editing *.component.yml, twig or libraries.yml: drush cr. After editing JSX/SCSS: rebuild (npm run watch does it).
  • Component props are validated on every render, a wrong type is a visible error. Fix the schema or the caller, do not loosen the schema to silence it.
  • If something does not show up, follow the checklist in Build.

Variants with html_cva() ​

When a prop is a choice (enum in the component.yml), map it to classes with html_cva(), a Twig function of Drupal 11.4 and later (Frame needs 11.4, so it is always there). One place lists the base class, the classes of each value and the defaults. Name the variants like the values of the prop: the editor shows the enum as a select, so what the editor picks is what the template looks up.

yaml
# button.component.yml
variant: { type: string, enum: [primary, outline, text], meta:enum: { primary: Filled, outline: Outline, text: 'Text only' } }
size: { type: string, enum: [s, m, l] }
twig
{% set cva = html_cva('button-link', {
  variant: { primary: 'button-link--primary', outline: 'button-link--outline', text: 'button-link--text' },
  size: { s: 'button-link--s', m: 'button-link--m', l: 'button-link--l' },
}, [], {variant: 'primary', size: 'm'}) %}
<a {{ attributes.addClass(cva.apply({variant: variant|default(null), size: size|default(null)}|filter(v => v is not null))) }} href="{{ url }}">{{ label }}</a>
  • The arguments are the base classes, the variants, the compound variants and the default variants. apply() returns the classes as one string.
  • Pass |default(null) and drop the empty ones with |filter(v => v is not null): a prop that is left out then gets the default variant (a null value would trigger a PHP deprecation). A value that is not a variant adds no class.
  • A class may be a Frame utility, for example 'frame-px-m frame-py-s' for a size, next to your own classes.
  • A compound variant adds classes for a combination: [{variant: 'outline', size: ['l'], class: 'button-link--wide-outline'}]. It needs both props to be given, the default variants do not count.
  • One chain: component.yml -> the editor -> the template. Mark the look prop with variant_prop: variant (see Variants) and the editor offers its enum as the Variant select and as looks in the Blocks panel. The template looks the same name up in html_cva(). A component with core's variants: gets the chosen one as variant in the template, the same way. Adding a look is one line in the YAML and one in the html_cva() call, with the same name.
  • The test ComponentCvaTest::testEveryEnumValueHasAVariant checks that every value of an enum prop given to apply() has a key in the call.
  • The classes Frame adds from the editor (spacing, background, position) are not classes of the template: Frame passes them as style and data-* in attributes, so attributes.addClass(cva...) keeps both and the variant classes never clash with them. Frame utility classes written in the html_cva() call are fine too.

Notice, Badge, Button and Heading of the base theme are written like this. In the editor each look is a choice of the Variant select, and the Blocks panel lists them under the block:

The looks of a block as a group under it in the Blocks panel

The variants of Button, Notice and Badge on the canvas