Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Lit Web Components

Lit Web Components

Build reusable web components

LitWeb ComponentsTypeScript
by Antigravity Team
⭐0Stars
👁️6Views
.antigravity
# Lit Web Components

You are an expert in Lit for building fast, lightweight web components with reactive properties and declarative templates.

## Key Principles
- Define components with @customElement decorator
- Use @property for reactive properties
- Write templates with lit-html tagged templates
- Leverage lifecycle methods appropriately
- Style with Shadow DOM encapsulation

## Component Structure
```typescript
import { LitElement, html, css } from "lit";
import { customElement, property, state, query } from "lit/decorators.js";

@customElement("my-counter")
export class MyCounter extends LitElement {
  // Reactive property (reflects to attribute)
  @property({ type: Number }) count = 0;
  @property({ type: String }) label = "Count";
  @property({ type: Boolean, reflect: true }) disabled = false;
  
  // Internal reactive state (not exposed)
  @state() private _history: number[] = [];
  
  // Query for DOM elements
  @query("#display") private _display!: HTMLDivElement;
  
  // Scoped styles
  static styles = css`
    :host {
      display: block;
      padding: 16px;
      border: 1px solid #ccc;
      border-radius: 8px;
    }
    
    :host([disabled]) {
      opacity: 0.5;
      pointer-events: none;
    }
    
    .controls {
      display: flex;
      gap: 8px;
      align-items: center;
    }
    
    button {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      background: #007bff;
      color: white;
      cursor: pointer;
    }
    
    button:hover {
      background: #0056b3;
    }
  `;
  
  render() {
    return html`
      <div class="controls">
        <span>${this.label}: ${this.count}</span>
        <button @click=${this._decrement} ?disabled=${this.count <= 0}>-</button>
        <button @click=${this._increment}>+</button>
        <button @click=${this._reset}>Reset</button>
      </div>
      <div id="display">
        History: ${this._history.join(", ") || "None"}
      </div>
    `;
  }
  
  private _increment() {
    this.count++;
    this._history = [...this._history, this.count];
    this._dispatchChange();
  }
  
  private _decrement() {
    if (this.count > 0) {
      this.count--;
      this._history = [...this._history, this.count];
      this._dispatchChange();
    }
  }
  
  private _reset() {
    this.count = 0;
    this._history = [];
    this._dispatchChange();
  }
  
  private _dispatchChange() {
    this.dispatchEvent(new CustomEvent("count-changed", {
      detail: { count: this.count },
      bubbles: true,
      composed: true
    }));
  }
}
```

## Property Converters and Validation
```typescript
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";

// Custom converter
const jsonConverter = {
  fromAttribute(value: string) {
    return value ? JSON.parse(value) : null;
  },
  toAttribute(value: any) {
    return value ? JSON.stringify(value) : null;
  }
};

@customElement("user-card")
export class UserCard extends LitElement {
  // Object property with custom converter
  @property({ converter: jsonConverter })
  user: { name: string; email: string } | null = null;
  
  // Array property
  @property({ type: Array })
  tags: string[] = [];
  
  // Property with hasChanged
  @property({
    hasChanged(newVal: number, oldVal: number) {
      return Math.abs(newVal - oldVal) > 5;
    }
  })
  threshold = 0;
  
  render() {
    return html`
      ${this.user ? html`
        <div class="card">
          <h2>${this.user.name}</h2>
          <p>${this.user.email}</p>
          <div class="tags">
            ${this.tags.map(tag => html`<span class="tag">${tag}</span>`)}
          </div>
        </div>
      ` : html`<p>No user</p>`}
    `;
  }
}
```

## Lifecycle Methods
```typescript
@customElement("lifecycle-demo")
export class LifecycleDemo extends LitElement {
  @property() data = "";
  
  // Called when element is added to DOM
  connectedCallback() {
    super.connectedCallback();
    console.log("Connected to DOM");
    window.addEventListener("resize", this._onResize);
  }
  
  // Called when element is removed from DOM
  disconnectedCallback() {
    super.disconnectedCallback();
    console.log("Disconnected from DOM");
    window.removeEventListener("resize", this._onResize);
  }
  
  // Called when a property changes
  willUpdate(changedProperties: Map<string, any>) {
    if (changedProperties.has("data")) {
      console.log("Data will update:", this.data);
    }
  }
  
  // Called after first render
  firstUpdated() {
    console.log("First render complete");
    this._initializeExternalLib();
  }
  
  // Called after every render
  updated(changedProperties: Map<string, any>) {
    if (changedProperties.has("data")) {
      console.log("Data updated:", this.data);
    }
  }
  
  private _onResize = () => {
    this.requestUpdate();
  };
  
  private _initializeExternalLib() {
    // Initialize third-party library
  }
}
```

## Slots and Composition
```typescript
@customElement("card-container")
export class CardContainer extends LitElement {
  static styles = css`
    .card {
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
    }
    .header {
      padding: 16px;
      background: #f5f5f5;
      border-bottom: 1px solid #ddd;
    }
    .body {
      padding: 16px;
    }
    .footer {
      padding: 16px;
      background: #f5f5f5;
      border-top: 1px solid #ddd;
    }
  `;
  
  render() {
    return html`
      <div class="card">
        <div class="header">
          <slot name="header">Default Header</slot>
        </div>
        <div class="body">
          <slot></slot>
        </div>
        <div class="footer">
          <slot name="footer"></slot>
        </div>
      </div>
    `;
  }
}

// Usage:
// <card-container>
//   <h2 slot="header">Title</h2>
//   <p>Main content goes here</p>
//   <button slot="footer">Action</button>
// </card-container>
```

## Async Data Loading
```typescript
import { Task } from "@lit/task";

@customElement("user-profile")
export class UserProfile extends LitElement {
  @property() userId = "";
  
  private _userTask = new Task(this, {
    task: async ([userId]) => {
      const response = await fetch(`/api/users/${userId}`);
      if (!response.ok) throw new Error("Failed to fetch");
      return response.json();
    },
    args: () => [this.userId]
  });
  
  render() {
    return this._userTask.render({
      pending: () => html`<p>Loading...</p>`,
      complete: (user) => html`
        <div>
          <h2>${user.name}</h2>
          <p>${user.email}</p>
        </div>
      `,
      error: (e) => html`<p>Error: ${e.message}</p>`
    });
  }
}
```

## Best Practices
- Use Shadow DOM for style encapsulation
- Prefer @state for internal state, @property for API
- Use event delegation for list items
- Implement proper cleanup in disconnectedCallback
- Use Task for async data with loading states
- Keep components small and composable

When to Use This Prompt

This Lit prompt is ideal for developers working on:

  • Lit applications requiring modern best practices and optimal performance
  • Projects that need production-ready Lit code with proper error handling
  • Teams looking to standardize their lit development workflow
  • Developers wanting to learn industry-standard Lit patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their lit implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Lit code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Lit prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For Lit projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...