agentleFS
UI5UI5/webcomponents-react/CLAUDE.md

webcomponents-react

CLAUDE.md542 starsChanged 14 months agoApache-2.0View on GitHub

UI5 Web Components for React is a React wrapper library for SAP's UI5 Web Components. It provides Fiori-compliant React components by wrapping native UI5 Web Components with React-specific implementations. The project is a monorepo managed with Lerna and Yarn workspaces. Web components emit CustomEvents with data in the detail property: For enriching events with additional data (internal use): UI5 Web Components update internal state before firing events. For fully controlled components, call e.preventDefault() in the handler to prevent internal state…

The file

We split this CLAUDE.md into the rules it gives an agent

8 rules. About 0 are common, 3 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When a component needs both a forwarded ref and internal access to the same DOM node, use useSyncRef() instead of useRef():

    line 43
  2. Very specific:

    If the ref is just passed through without internal usage, forward it directly - no useSyncRef needed.

    line 61
  3. Very specific:

    When passing custom React components to slot props, they must forward the slot prop:

    line 65
  4. Distinctive:

    Use SAP CSS variables directly:

    line 101
  5. Very specific:

    Use yarn (not pnpm). For tools, use project binaries via yarn (e.g., yarn cypress, yarn eslint, yarn tsc).

    line 206
  6. Distinctive:

    Import assets for translations:

    line 393
  7. Very specific:

    Test with URL param: ?sap-ui-language=de

    line 399
  8. Distinctive:

    If a change could be considered breaking, inform the user.

    line 403

≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code when working with code in this repository.

Overview

UI5 Web Components for React is a React wrapper library for SAP's UI5 Web Components. It provides Fiori-compliant React components by wrapping native UI5 Web Components with React-specific implementations. The project is a monorepo managed with Lerna and Yarn workspaces.

Critical: Working with Web Components

Event Handling (MUST KNOW)

Web components emit CustomEvents with data in the detail property:

// ❌ WRONG - won't work with web components
const handleChange = (e) => {
  console.log(e.selectedOption); // undefined!
  console.log(e.value); // undefined!
};

// ✅ CORRECT - access via e.detail
const handleChange = (e) => {
  console.log(e.detail.selectedOption);
  console.log(e.detail.value);
};

For enriching events with additional data (internal use):

import { enrichEventWithDetails } from '@ui5/webcomponents-react-base/internal/utils';

onLoadMore(enrichEventWithDetails(e, { rowCount, totalRowCount }));

Controlled Components (MUST KNOW)

UI5 Web Components update internal state before firing events. For fully controlled components, call e.preventDefault() in the handler to prevent internal state updates (e.g., Input.onInput, CheckBox.onChange, Select.onChange, Dialog.onBeforeClose).

Ref Handling (MUST KNOW)

When a component needs both a forwarded ref and internal access to the same DOM node, use useSyncRef() instead of useRef():

import { useSyncRef } from '@ui5/webcomponents-react-base/internal/hooks';

const MyComponent = forwardRef((props, ref) => {
  const [componentRef, internalRef] = useSyncRef(ref);

  useEffect(() => {
    // internalRef gives stable access to the DOM node inside the component
    internalRef.current?.focus();
  }, []);

  // componentRef is passed to the DOM element so both the forwarded ref and internalRef stay in sync
  return <div ref={componentRef} />;
});

If the ref is just passed through without internal usage, forward it directly - no useSyncRef needed.

Slot Props (MUST KNOW)

When passing custom React components to slot props, they must forward the slot prop:

// ❌ WRONG - slot won't render correctly
const CustomHeader = ({ children }) => <div>{children}</div>;

// ✅ CORRECT - forwards slot prop to root element
const CustomHeader = ({ children, slot }) => <div slot={slot}>{children}</div>;

// Usage
<Dialog header={<CustomHeader>Title</CustomHeader>} />;

Note: React Portals are NOT supported in slot props (will log warning).

CSS and Shadow DOM Styling

Web component internals are in Shadow DOM. Use ::part() pseudo-element:

/* ❌ WRONG - can't pierce shadow DOM */
.myButton button {
  background: red;
}

/* ✅ CORRECT - use ::part() for shadow DOM */
.myCheckbox::part(root) {
  display: flex;
  width: unset;
}

.actionSheet::part(content) {
  padding: 0.1875rem 0.375rem;
}

Use SAP CSS variables directly:

.myComponent {
  background: var(--sapBackgroundColor);
  color: var(--sapTextColor);
  border-radius: var(--sapElement_BorderCornerRadius);
  font-family: var(--sapFontFamily);

  /* Semantic colors */
  --success: var(--sapPositiveColor);
  --error: var(--sapNegativeColor);
  --warning: var(--sapCriticalColor);
  --info: var(--sapInformativeColor);
}

Internal component variables use --_ui5wcr* prefix:

const style = {
  '--_ui5wcr-AnalyticalTableRowHeight': `${rowHeight}px`,
} as CSSProperties;

SSR Compatibility

Components must work in both SPA and SSR environments. Wrappers use suppressHydrationWarning because web component internal state doesn't serialize consistently.

CSS Modules

Component styles use CSS Modules (.module.css files). The corresponding .css.ts files are auto-generated by the build system and gitignored (src/**/*.css.ts in each package's .gitignore). Never create or edit .css.ts files manually — only create the .module.css source file.

Core Architecture

Base Package Imports

The @ui5/webcomponents-react-base package uses subpath exports. Always use the specific subpath, not the root import:

// ❌ WRONG - don't use root import
import { useSyncRef } from '@ui5/webcomponents-react-base';

// ✅ CORRECT - use subpath exports
import { useI18nBundle, useViewportRange } from '@ui5/webcomponents-react-base/hooks';
import {
  useSyncRef,
  useStylesheet,
  useIsRTL,
  useIsomorphicLayoutEffect,
  useCurrentTheme,
} from '@ui5/webcomponents-react-base/internal/hooks';
import { debounce, throttle, enrichEventWithDetails } from '@ui5/webcomponents-react-base/internal/utils';
import { Device } from '@ui5/webcomponents-react-base/Device';

Available subpath exports:

  • ./hooks - Public hooks: useI18nBundle, useViewportRange
  • ./internal/hooks - Internal hooks: useSyncRef, useStylesheet, useIsRTL, useIsomorphicLayoutEffect, useCurrentTheme
  • ./internal/utils - Utilities: debounce, throttle, enrichEventWithDetails
  • ./Device - Device detection utilities
  • ./types - TypeScript types

Package Structure

Packagenpm NameDescription
main@ui5/webcomponents-reactReact wrappers + custom components
base@ui5/webcomponents-react-baseCore utilities, hooks, wrapper infrastructure
charts@ui5/webcomponents-react-chartsChart components (recharts-based)
compat@ui5/webcomponents-react-compatLegacy components
cli@ui5/webcomponents-react-cliWrapper generation, codemods
cypress-commands@ui5/webcomponents-cypress-commandsTesting utilities
ai@ui5/webcomponents-ai-reactAI component wrappers
mcp-server@ui5/webcomponents-react-mcpMCP server exposing component APIs/docs to AI agents

Main Package Structure

  • src/webComponents/: Auto-generated wrappers (Button, Input, Dialog, etc.)
  • src/components/: Custom React components (AnalyticalTable, ObjectPage, FilterBar)
  • src/enums/: TypeScript enums
  • src/i18n/: Internationalization

Wrapper Architecture

The withWebComponent HOC (packages/base/src/internal/wrapper/withWebComponent.tsx):

withWebComponent<Props, RefType>(
  tagName: string,           // 'ui5-button'
  regularProperties: string[], // String/number attributes
  booleanProperties: string[], // Boolean attributes (React 18 vs 19 handling)
  slotProperties: string[],    // Named slots
  eventProperties: string[]    // Custom events
)

React version handling:

  • React 19+: Native JSX event attributes, direct boolean passing
  • React 18: Manual addEventListener, conditional boolean attributes

Working in This Repo

Use yarn (not pnpm). For tools, use project binaries via yarn (e.g., yarn cypress, yarn eslint, yarn tsc).

Run prettier on edited files after changes.

CSS Modules: The .module.css.ts files (containing styleData and classNames) are automatically regenerated when Storybook or the dev server is running. You do not need to manually rebuild them after editing a .module.css file — the bundler handles it.

Testing single files: Try yarn test first. If that doesn't work, use yarn cypress run --spec <path>. If still stuck, ask.

yarn start           # Storybook (localhost:6006)
yarn test            # Cypress component tests
yarn test:pw         # Playwright component tests
yarn lint            # ESLint
yarn prettier:all    # Format all files

Tests

See also Testing guide for more details.

Always write new tests in Playwright. For large changes to existing Cypress tests, migrate the test to Playwright instead of updating the Cypress version.

The repo uses two component-test runners side by side:

  • Cypress — ComponentName.cy.tsx co-located next to index.tsx. Run with yarn test (or yarn cypress). Config: cypress.config.ts.
  • Playwright — ComponentName.spec.tsx under a test/ subfolder (packages/main/src/components/<Component>/test/*.spec.tsx). Run with yarn test:pw (yarn test:pw:open for the UI). Config: playwright.config.ts.

The section below documents the Cypress setup; the same web-component selector/shadow-DOM principles apply to Playwright (its locators pierce shadow roots by default).

File Structure

Tests are co-located with components: ComponentName.cy.tsx next to index.tsx.

src/components/ActionSheet/
├── index.tsx
├── ActionSheet.cy.tsx      # Component tests
├── ActionSheet.stories.tsx # Storybook stories
└── ActionSheet.mdx         # Docs page

Running Tests

yarn test                              # All tests
yarn cypress run --spec <path>         # Single file
yarn cypress open                      # Interactive mode

Test Pattern

import { ComponentName } from './index.js';

describe('ComponentName', () => {
  it('description', () => {
    cy.mount(<ComponentName prop="value" />);
    cy.get('[ui5-button]').should('be.visible');
    cy.findByText('Click').click();
  });
});

Key Patterns

  • Shadow DOM enabled: includeShadowDom: true in config - queries pierce shadow DOM automatically
  • Use web component selectors: [ui5-button], [ui5-dialog], [ui5-responsive-popover]
  • Use existing data attributes: [data-component-name="..."], [data-row-index="0"] (don't create new ones just for tests)
  • Spy on events: const onEvent = cy.spy().as('onEvent'), then cy.get('@onEvent').should('have.been.calledOnce')
  • Keyboard testing: cy.realPress('ArrowDown'), cy.realPress('Enter')

Cypress Commands Package

@ui5/webcomponents-cypress-commands provides helpers for web components:

cy.get('[ui5-input]').typeIntoUi5Input('text');
cy.get('[ui5-select]').ui5SelectOption('Option 1');

Stories (Storybook)

File Structure

Stories are co-located: ComponentName.stories.tsx next to component. MDX docs pages (ComponentName.mdx) provide additional documentation.

Running Storybook

yarn start    # Opens localhost:6006

Story Pattern (CSF 3)

import type { Meta, StoryObj } from '@storybook/react-vite';
import { ComponentName } from './index.js';

const meta = {
  title: 'Category / ComponentName', // e.g., 'Inputs / Button'
  component: ComponentName,
  argTypes: {
    children: { control: { disable: true } }, // Disable controls for complex props
    slotProp: { control: { disable: true } },
  },
  args: {
    // Default prop values
    design: SomeEnum.Default,
  },
  tags: ['package:@ui5/webcomponents'], // Metadata tags
} satisfies Meta<typeof ComponentName>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Default: Story = {}; // Uses args from meta

export const WithCustomRender: Story = {
  render(args) {
    const [state, setState] = useState(false);
    return <ComponentName {...args} open={state} />;
  },
};

MDX Docs Pages

import { ControlsWithNote, DocsHeader, Footer } from '@sb/components';
import { Canvas, Meta } from '@storybook/addon-docs/blocks';
import * as ComponentStories from './ComponentName.stories';

<Meta of={ComponentStories} />
<DocsHeader of={ComponentStories} subComponents={['ChildComponent']} />

## Example

<Canvas of={ComponentStories.Default} />

## Properties

<ControlsWithNote of={ComponentStories.Default} />

<Footer />

Story Tags

  • package:@ui5/webcomponents - Web component wrapper
  • package:@ui5/webcomponents-react - Custom component
  • extends:@ui5/webcomponents + cem-module:ModuleName - Extended web component

TypeScript Patterns

Component Interface Pattern

// Three-tier pattern used consistently:
interface ButtonAttributes {
  /* web component props */
}
interface ButtonDomRef extends Required<ButtonAttributes>, Ui5DomRef {
  // DOM methods like focus(), click()
}
interface ButtonPropTypes extends ButtonAttributes, Omit<CommonProps, keyof ButtonAttributes> {
  // React additions: slots, children
}

Slot Type

badge?: UI5WCSlotsNode;

Internationalization

import { useI18nBundle } from '@ui5/webcomponents-react-base/hooks';

const i18nBundle = useI18nBundle('@ui5/webcomponents-react');
const text = i18nBundle.getText(CLEAR);

// Also available for web components bundle
const wcBundle = useI18nBundle('@ui5/webcomponents');

Import assets for translations:

import '@ui5/webcomponents-react/dist/Assets.js';

Test with URL param: ?sap-ui-language=de

Breaking Changes

If a change could be considered breaking, inform the user.

Accessibility

See UI5 Web Components Accessibility.

Web component wrappers: Accessibility handled by UI5 Web Components. Wrappers pass through accessibleName, accessibleNameRef, ARIA props.

Custom components (AnalyticalTable, ObjectPage, FilterBar, etc.) combine web components with standard HTML elements (div, span, etc.). These require manual accessibility implementation:

  • ARIA roles/attributes on standard HTML elements
  • Keyboard navigation
  • Screen reader announcements
  • Focus management

Abstract Components

Components marked with @abstract in JSDoc (e.g., SuggestionItem, Tab, WizardStep, ToolbarButton) are placeholders that pass props to their parent's shadow root. They don't render their own DOM.

Implications:

  • Not stylable - style, className have no visual effect
  • Native HTML attributes - title, data-*, etc. apply to the placeholder, not the rendered element
  • Native events - registered on the placeholder element, not the actual rendered component
  • getDomRef() - returns the parent's DOM element representing this item, not the placeholder itself

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.