Get Started
This tutorial will guide you step-by-step through creating, registering, templating, and using your first reactive custom element using @beforesemicolon/web-component.
Step 1: Declaring the Component Class
To create a new component, declare a class that extends WebComponent.
1import { WebComponent } from '@beforesemicolon/web-component'2 3class MyButton extends WebComponent {4 // Component logic goes here5}Step 2: Defining the Custom Element Tag
Register the component class in the global CustomElementRegistry using the standard customElements.define method.
Custom element names MUST contain at least one hyphen (-) and should be written in lowercase (kebab-case) to prevent conflicts with standard HTML elements.
1customElements.define('my-button', MyButton)Step 3: Adding a Template
To render content, define a render() method in your class. The method should return an HtmlTemplate (created using the html tagged template literal), a plain HTML string, a native DOM Node, or void.
1import { WebComponent, html } from '@beforesemicolon/web-component'2 3class MyButton extends WebComponent {4 render() {5 return html` <button type="button">Click Me</button> `6 }7}8 9customElements.define('my-button', MyButton)Step 4: Using the Custom Element in HTML
Once the custom element is registered, you can place the <my-button> tag anywhere in your HTML document.
1<!doctype html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <title>WebComponent Tutorial</title>6 <!-- Include the compiled script containing your component definitions -->7 <script type="module" src="./my-button.js"></script>8 </head>9 <body>10 <my-button></my-button>11 </body>12</html>Next Steps
Now that you have built your first web component, explore the core features that make @beforesemicolon/web-component powerful:
- Reactive Props: Pass data into your components and handle attribute updates.
- Reactive State: Manage internal state and automatically trigger surgical DOM updates.
- Lifecycle Hooks: Run setup and cleanup code with
onMountandonDestroy.