React Advanced

Web Components Integration

Using web components in React, wrapping custom elements, and framework interop.

Advertisement

Web Components Integration

Using web components in React, wrapping custom elements, and framework interop.

Overview

Web components are browser-native reusable components that work across frameworks.

Key Concepts

  • Custom Elements — Define new HTML elements
  • Shadow DOM — Encapsulated DOM and styling
  • React Wrapper — Adapt web components for React
  • Props to Attributes — Convert React props to HTML attributes
  • Events — Listen to custom events from web components

Code Examples

// Wrapper for web component
function MyWebComponent({ value, onChange, ...props }) {
  const ref = useRef(null);

  useEffect(() => {
    const element = ref.current;
    const handleChange = (e) => onChange?.(e.detail);
    
    element.addEventListener('change', handleChange);
    return () => element.removeEventListener('change', handleChange);
  }, [onChange]);

  return <my-web-component ref={ref} value={value} {...props} />;
}

// Usage in React
function App() {
  const [value, setValue] = useState('');
  
  return (
    <MyWebComponent 
      value={value} 
      onChange={setValue}
      data-testid="custom-input"
    />
  );
}

// Register custom element in React
class MyElement extends HTMLElement {
  connectedCallback() {
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>:host { display: block; }</style>
      <slot></slot>
    `;
  }
}

customElements.define('my-element', MyElement);

Practice

Create a web component library and integrate it into a React application.