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?