Blog>
Snippets

Integrating React with Web Components

Show how to integrate Web Components within a React application without losing the reactivity and state management of React.
class MyWebComponent extends HTMLElement {
  // Web component code here
}

window.customElements.define('my-web-component', MyWebComponent);
This is the definition of a simple Web Component using the Custom Elements API. It registers 'my-web-component' as a new custom HTML element.
import React, { useEffect, useRef, useState } from 'react';

class WebComponentWrapper extends React.Component {
  render() {
    return <my-web-component ref={this.props.forwardedRef} {...this.props}></my-web-component>;
  }
}

function WebComponentWithReact(props) {
  const webComponentRef = useRef(null);
  const [state, setState] = useState('');

  useEffect(() => {
    if (webComponentRef.current) {
      webComponentRef.current.addEventListener('customEvent', e => {
        setState(e.detail);
      });
    }
  }, []);

  return <WebComponentWrapper forwardedRef={webComponentRef} propFromState={state} {...props} />;
}

export default WebComponentWithReact;
This is a React component that wraps the Web Component. It sets up a ref to the Web Component and handles any custom events using useEffect. It maintains React's state and reactivity by updating a state whenever a custom event is received from the Web Component.
/* In your main React application file */
import WebComponentWithReact from './WebComponentWithReact';

function App() {
  return (
    <div>
      {/* Use the React component wrapper to include the Web Component in your application */}
      <WebComponentWithReact someProp="someValue" />
    </div>
  );
}

export default App;
This code snippet shows how to use the React component that wraps the Web Component within a larger React application. A custom prop 'someProp' is passed to the Web Component through the wrapper.
/* Example CSS that could apply styles to the Web Component */
my-web-component {
  border: 1px solid #333;
  padding: 10px;
}
This is an example CSS snippet that styles the custom Web Component when it is used in a webpage or a React application.