3

I am new to web Components and trying to integrate web components with React.

There is a scenario where I have to pass button from react to web-component. For click event of the button, I have attached a handler which will perform some action/manipulation in react. So it has to be passed from react to web-component.

Following is the sample code:

React component:

import React, {Component} from 'react';

export class Sample extends Component {

    handleButtonOneClick = () => {
        alert(" ButtonOne Action happened, perform some action in React!!!!!!!!!!!");
    };
    handleButtonTwoClick = () => {
        alert("ButtonTwo Action happened, perform some action in React!!!!!!!!!!!");
    };

    render() {
        return (
                <my-sample-element >
                    <button id="button-one" onClick={this.handleButtonOneClick}> Button 1</button>
                    <button id="button-two" onClick={this.handleButtonTwoClick}> Button 2</button>
                </my-sample-element>
        );
    }
}

Web-component:

export class CustomSampleElement extends HTMLElement {

    constructor() {
        super();
    }

    connectedCallback() {
        const shadowDOM = this.attachShadow({mode: 'open'});
        const divElement = document.createElement('div');

        const childrenNode = this.children;
        while (childrenNode.length) {
            divElement.appendChild(childrenNode[0]);
        }

        shadowDOM.appendChild(divElement);
    }
}

customElements.define('my-sample-element', CustomSampleElement);

But the event handler is not getting added in the web-component. I don’t know why. Any idea, how to solve this issue?

Suba V R
  • 31
  • 2
  • Here: https://stackoverflow.com/questions/42274721/shadow-dom-and-reactjs add https://stackoverflow.com/questions/37866237/click-event-not-firing-when-react-component-in-a-shadow-dom – Oleg Sep 19 '19 at 13:35
  • 2
    You should not call `attachShadow` in the `connectedCallback` since that is called *every* time your component is placed in the dom. So if you move the component it will be called twice and the second time it will fail. It is best to call `attachShadow` in the constructor. Also use the `` element in your shadow DOM instead of moving all children. – Intervalia Sep 19 '19 at 15:05

0 Answers0