JSFiddle - React, Tailwind, and code Playground

by melihsahin

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Component</title>
</head>
<body>
  <h1>Button Component</h1>
  <custom-button>Click!</custom-button>
  <script src="button.js"></script>
</body>
</html>

JavaScript

class CustomButton extends HTMLElement {
    constructor() {
        super();
        // Attach shadow DOM
        this.attachShadow({
            mode: 'open'
        });

        // Add click event listener
        this.addEventListener('click', this.handleClick.bind(this));
    }

    // Handle click event
    handleClick() {
        alert('Button clicked!');
    }

    connectedCallback() {
        // create the component to render
        this.shadowRoot.innerHTML = `
     <style>
      .custom-button {
       padding: 10px 20px;
       background-color: #007bff;
       color: #fff;
       border: none;
       border-radius: 5px;
        cursor: pointer;
      }
      .custom-button:hover {
       background-color: #0056b3;
       }
      </style>
    <button class="custom-button"><slot></slot></button>`;
    }
}
// component is defined
customElements.define('custom-button', CustomButton);