Web Components Adoption Runway for React Primitives
This adoption runway is a phased, incremental strategy to migrate React primitives (e.g., buttons, inputs, modals) into framework-agnostic Web Components (WCs). It uses @r2wc/react-to-webcomponent to wrap React components effortlessly, ensuring:
- Reusability: WCs work in React, Vue, Vanilla JS, etc.
- Accessibility (a11y): Preserved via Shadow DOM best practices (e.g.,
delegatesFocus, ARIA delegation, slotted content).
- Testing: Introduces custom element testing with
@web/test-runner for unit/integration and Playwright for E2E/a11y.
- Minimal disruption: No big-bang rewrite; start with pilots.
The runway is divided into 5 phases, with milestones, tools, code snippets, and success criteria. Estimated timeline: 4-8 weeks for a mid-sized team.
Prerequisites & Tooling Setup (Week 0)
Install core tools in a monorepo (e.g., Turborepo) or dedicated packages/web-components/ folder.
npm init -y
npm i @r2wc/react-to-webcomponent react react-dom
npm i -D vite @web/test-runner @web/components-testing @playwright/test @axe-core/playwright # Testing
npm i -D @rollup/plugin-node-resolve rollup-plugin-peer-deps-external # Bundling
npm i -D typescript @types/react eslint eslint-plugin-lit-a11y # TS/Linting
Vite Config (vite.config.ts for dev/build):
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: { lib: { entry: resolve(__dirname, 'src/index.ts'), name: 'MyComponents', formats: ['es'] } },
});
tsconfig.json (key excerpts):
{ "compilerOptions": { "declaration": true, "jsx": "react-jsx", "moduleResolution": "bundler" } }
A11y Checklist (enforce via ESLint):
- Delegate
tabindex, role, aria-* to shadow root/light DOM.
- Use
<slot> for user content.
- Enable
shadowRoot.delegatesFocus = true.
- Test with axe-core.
Phase 1: Foundation & First Pilot (Week 1)
Goal: Wrap a simple React primitive (e.g., Button) as WC. Validate a11y and basic testing.
Steps:
- Create React primitive:
src/Button.tsx (your existing design system button).
- Wrap as WC:
src/components/WcButton.tsx.
// src/Button.tsx (React primitive - assume it has props: variant, disabled, onClick, children)
import React from 'react';
export const Button = ({ variant = 'primary', disabled, onClick, children }: ButtonProps) => (
<button className={`btn btn-${variant}`} disabled={disabled} onClick={onClick}>
{children}
</button>
);
// src/components/WcButton.tsx
import React, { useEffect, useRef } from 'react';
import reactToWebComponent from '@r2wc/react-to-webcomponent';
import { Button, ButtonProps } from '../Button';
class WcButton extends HTMLElement {
private shadowRoot: ShadowRoot;
private reactRoot: React.ComponentType<ButtonProps>;
constructor() {
super();
this.attachShadow({ mode: 'open', delegatesFocus: true }); // A11y: Delegate focus
this.reactRoot = reactToWebComponent(Button, React, ReactDOM);
}
connectedCallback() {
const props: ButtonProps = {
variant: this.getAttribute('variant') as any || 'primary',
disabled: this.hasAttribute('disabled'),
onClick: (e: MouseEvent) => this.dispatchEvent(new CustomEvent('click', { detail: e })),
children: this.innerHTML, // Slotted content
};
const root = this.reactRoot(props);
ReactDOM.render(<root />, this.shadowRoot);
}
}
customElements.define('wc-button', WcButton);
- Basic Test (
test/wc-button.test.ts with @web/test-runner):
import { expect, fixture, html } from '@web/test-runner';
describe('WcButton', () => {
it('renders and is accessible', async () => {
const el = await fixture(html`<wc-button variant="primary">Click</wc-button>`);
expect(el.shadowRoot!.querySelector('button')!.textContent).to.equal('Click');
expect(el.getAttribute('role')).to.be.null; // Delegated to shadow
});
});
Run: npm run test (config in web-test-runner.config.mjs).
Milestone: Deploy to Storybook or demo page. Use in React app: <wc-button>Click</wc-button>. Pass axe-core scan.
Phase 2: Expand to Stateful Primitives (Weeks 1-2)
Goal: Wrap complex primitives (e.g., Input, Modal) with props/state syncing.
Enhancements:
- Props Observation: Use
MutationObserver or connectedCallback for dynamic props.
- Events: Dispatch CustomEvents for React callbacks.
Example: Stateful Input.
// WcInput.tsx (excerpt)
class WcInput extends HTMLElement {
connectedCallback() {
// ... similar to Button
props.onChange = (e: InputEvent) => this.dispatchEvent(new CustomEvent('change', { detail: e }));
// Observe attribute changes
const observer = new MutationObserver(() => this.renderReact(props));
observer.observe(this, { attributes: true });
}
}
A11y Focus:
- Inputs:
aria-label on host if no label slotted.
- Modals:
aria-modal, trap focus in Shadow DOM.
Testing:
- Integration: Simulate user interactions.
it('emits change event', async () => {
const el = await fixture(html`<wc-input></wc-input>`);
const input = el.shadowRoot!.querySelector('input');
input!.value = 'test';
input!.dispatchEvent(new Event('input'));
await el.updateComplete;
expect(el.dispatchEvent).to.have.been.calledWithMatch({ type: 'change' });
});
Milestone: 3-5 WCs. CI/CD with tests. Use in non-React app (e.g., Vanilla JS).
Phase 3: Full Testing Suite (Week 3)
Goal: Production-grade testing for custom elements.
Test Pyramid:
| Level | Tool | Coverage |
|---|
| Unit | @web/test-runner | Shadow DOM, props, events (80%) |
| Integration | @web/components-testing + MSW | API mocks, slotted content |
| E2E/A11y | Playwright + axe-core | Keyboard nav, screen readers |
| Visual | Playwright + Percy | Regression-free |
Playwright Setup (playwright.config.ts):
import { defineConfig } from '@playwright/test';
import axe from '@axe-core/playwright';
export default defineConfig({
use: { axe: { rules: { 'color-contrast': { enabled: true } } } },
});
Example E2E:
test('wc-modal is accessible', async ({ page }) => {
await page.goto('/demo.html');
await expect(page.locator('wc-modal')).toHaveJSHandle('el => el.shadowRoot.delegatesFocus');
await axe(page); // Fails on violations
});
Milestone: 90% test coverage. Flaky test budget <5%.
Phase 4: Design System Integration & Scale (Weeks 4-5)
Goal: Catalog WCs, guidelines for wrapping more primitives.
Guidelines Doc:
- Wrapping Recipe: React → WC template (code snippet above).
- Props: Kebab-case attrs (e.g.,
aria-label), JSON for complex (e.g., data-props).
- Slots:
<slot name="icon"></slot> for composition.
- Theming: CSS Custom Properties (e.g.,
--primary-color).
Migration Path:
React App ─┐
├─ Storybook (mixed React/WC)
Vanilla ───┘
Bundle & Distribute: npm pack → unpkg CDN. Tree-shakable ES modules.
Milestone: 20+ WCs. Team training. A11y audit: 100% WCAG 2.1 AA.
Phase 5: Production Rollout & Maintenance (Week 6+)
Goal: Full adoption, monitoring.
- Observability: Sentry for WC errors; Lighthouse CI.
- Deprecation: Gradual React → WC swaps (codemod?).
- Upgrades: React 19 compatible via
@r2wc.
- Metrics: Adoption rate, perf (Shadow DOM encapsulation), a11y scores.
Risks & Mitigations:
| Risk | Mitigation |
|---|
| Shadow DOM styling leaks | :host { all: initial; } + part selectors |
| Hydration mismatch | Server-side render WCs with lit-html fallback |
| Bundle size | Lazy-load React in WC (dynamic import) |
Success Criteria:
- WCs used in 50% new features.
- Zero a11y regressions.
- Tests pass in evergreen browsers (Chrome 89+, Firefox 108+).
This runway scales your React primitives to a resilient, accessible component library. Start with Phase 1 today—fork the starter repo (imagine I linked one)! Questions? Let's iterate.