Example: ProductCard Component with Linked CSS File
Unlike the other components (UserCard, CounterComponent) that use inline CSS with <style> tags inside the component, this ProductCard component demonstrates how to link an external CSS file in Shadow DOM.
/src/styles/product-card.css<link rel="stylesheet" href="/src/styles/product-card.css">Click "Add to Cart" or "Details" buttons to see custom events in action.
No events yet. Interact with the products above.
/* src/styles/product-card.css */
:host {
display: block;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.product-card {
background: var(--color-background, white);
border-radius: 0;
/* ... more styles ... */
}
// src/components/ProductCard.js
class ProductCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
render() {
this.shadowRoot.innerHTML = `
<link rel="stylesheet" href="/src/styles/product-card.css">
<div class="product-card">
<!-- Component HTML -->
</div>
`;
}
}
// In your main.js or HTML
import './components/ProductCard.js';
// In your HTML
<product-card
name="Product Name"
price="99.99"
description="Description here"
rating="4.5"
stock="10"
category="Category">
</product-card>
render() {
this.shadowRoot.innerHTML = `
<style>
.card {
background: white;
/* All CSS here */
}
</style>
<div class="card">...</div>
`;
}
render() {
this.shadowRoot.innerHTML = `
<link rel="stylesheet" href="/src/styles/product-card.css">
<div class="card">...</div>
`;
}