Component-Based HTML Development
By the end of this lesson you will be able to look at a page design, spot the pieces that repeat, decide where each piece starts and ends, and build one reusable product card with plain HTML, a <template> and a few lines of JavaScript. You will use the same card in three different places on a page, and it will stay semantic and accessible in all of them.
What you should know first: Template Element (cloning with cloneNode(true)), Custom Data Attributes (dataset) and Semantic HTML5 Elements. The next lessons, starting with Web Components Introduction, turn the same ideas into real custom tags.
What a component is
A component is a piece of user interface with one job, written once and reused. It has its own markup, its own styles, sometimes its own behaviour, and a small list of inputs that change what it shows.
Think of a railway reservation form. Every passenger fills the same printed form: name, age, from, to. The layout never changes; only the values do. The printed form is the component, and each filled copy is an instance. The values written in the boxes are its inputs.
Frameworks such as React and Vue are built around components, but the idea does not need a framework. Learning it in plain HTML first makes every framework easier later.
Spotting components in a design
Open any shopping site and look for things that appear more than once with the same shape. Here is what you might find on the home page of a Rohtak gadget store:
| Piece | Where it repeats | Changes between copies |
|---|---|---|
| Navigation item | Header menu, footer menu | Text, link, current page |
| Product card | Deals grid, wishlist, "Recently viewed" | Product, size, button text |
| Price tag | Inside every card, in the cart, in a table | Price, MRP |
| Badge | On cards, on the order page | Text ("Sale", "New"), colour |
| Button | Everywhere | Label, style (primary, secondary) |
Components nest: a price tag sits inside a product card, which sits inside a grid. Combining small components into bigger ones is called composition.
A useful habit is the rule of three: write it once, notice the second copy, and extract a component on the third. Extract too early and nobody reuses it; too late and you fix ten slightly different copies.
Drawing the boundary
Deciding where a component starts and ends is the hard part. These questions help:
- Can you name its job in one short sentence? "Shows one product with its price and a buy button" is a good component. "Shows products and filters and the footer" is three components.
- Does it look after its inside only? A card decides the gap between its own heading and price. The page decides how wide the card is and the space between cards. Keep outer margins out of the component.
- What goes in, and what comes out? Data goes in as inputs. Messages come out as events, such as "the user wants to add this to the cart". The card should not update the cart itself.
- What changes with the context? Heading level is the classic example: under an
<h2>the card title should be an<h3>, under an<h3>it should be an<h4>. So heading level must be an input.
Props: inputs written as data attributes
Frameworks call a component's inputs props (short for properties). Without a framework, the natural place for props in HTML is a set of data-* attributes on a placeholder element. The placeholder marks where a component goes; the attributes say how it should look there.
Before writing code, write the component's contract: the props, which are required and their defaults. Your team reads this instead of your code.
| Prop | Attribute | Required | Default |
|---|---|---|---|
| Product id | data-product | Yes | none |
| Heading level | data-heading | No | 3 |
| Size | data-variant | No | full (or compact) |
| Button text | data-button | No | Add to cart |
Keep the real data (name, price) in one place, such as a JSON response from your server, and let the placeholder carry only an id.
Step 1: a small component with props
Start with the smallest piece, the price tag. Each placeholder carries a required data-price and an optional data-mrp (maximum retail price). One function reads the props, fills a copy of the template and replaces the placeholder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Price tag component</title>
<style>
.price-tag strong { color: #1b5e20; }
.price-tag s { color: #757575; margin-inline-start: 6px; }
.price-tag .off { background: #fff3e0; color: #e65100; margin-inline-start: 6px; padding: 0 4px; border-radius: 4px; }
td, th { border: 1px solid #ccc; padding: 4px 10px; text-align: left; }
</style>
</head>
<body>
<h1>School supplies, Jaipur</h1>
<p>Cricket bat, now only <span data-component="price-tag" data-price="2499" data-mrp="2999"></span>.</p>
<table>
<tr><th scope="row">Geometry box</th><td><span data-component="price-tag" data-price="180"></span></td></tr>
<tr><th scope="row">School bag</th><td><span data-component="price-tag" data-price="899" data-mrp="1199"></span></td></tr>
<tr><th scope="row">Water bottle</th><td><span data-component="price-tag"></span></td></tr>
</table>
<template id="price-tag">
<span class="price-tag"><strong class="now"></strong><s class="mrp"></s><span class="off"></span></span>
</template>
<script>
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
function renderPriceTag({ price, mrp }) {
const tag = document.querySelector("#price-tag").content.cloneNode(true);
const now = tag.querySelector(".now");
if (!(price > 0)) { // required prop missing
now.textContent = "Price on request";
tag.querySelector(".mrp").remove();
tag.querySelector(".off").remove();
return tag;
}
now.textContent = rupees.format(price);
if (mrp > price) { // optional prop
tag.querySelector(".mrp").textContent = "MRP " + rupees.format(mrp);
tag.querySelector(".off").textContent = Math.round((1 - price / mrp) * 100) + "% off";
} else {
tag.querySelector(".mrp").remove();
tag.querySelector(".off").remove();
}
return tag;
}
for (const spot of document.querySelectorAll('[data-component="price-tag"]')) {
const props = { price: Number(spot.dataset.price), mrp: Number(spot.dataset.mrp) };
spot.replaceWith(renderPriceTag(props));
}
</script>
</body>
</html>You should see the same price tag in a sentence and in three table cells. The bat shows "₹2,499 MRP ₹2,999 17% off". The geometry box has no MRP, so only its price shows. The water bottle has no price, so it shows "Price on request" instead of "₹NaN".
Step 2: the product card, composed and reused
Now build the bigger component. The product card composes the price tag: it calls renderPriceTag() instead of copying its markup. Fix a bug in the price tag once, and every card gets the fix.
The card is used in three places on one page:
- Deals of the day: full cards in a grid, with
<h3>titles. - Recently viewed: compact cards in an
<aside>, with no button. - Wishlist: inside a list under an
<h3>, so the titles must be<h4>, and the button says "Move to cart".
The card does not touch the cart. Its button sends an add-to-cart custom event that bubbles up, and the page listens once on document. You learned custom events in Custom Events.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Product card in three places</title>
<style>
body { font-family: system-ui, sans-serif; }
.layout { display: flex; flex-wrap: wrap; gap: 16px; }
main { flex: 3 1 320px; }
aside { flex: 1 1 200px; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; }
.card { border: 1px solid #ccc; border-radius: 8px; padding: 10px; display: grid; gap: 6px; }
.card img { width: 100%; height: auto; border-radius: 4px; }
.card :is(h3, h4) { font-size: 1rem; margin: 0; }
.card p { margin: 0; }
.card[data-variant="compact"] { grid-template-columns: 56px 1fr; align-items: center; margin-bottom: 8px; }
.card[data-variant="compact"] img { grid-row: span 2; }
.price-tag s { color: #757575; margin-inline-start: 6px; }
.wishlist { list-style: none; padding: 0; max-width: 220px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
</style>
</head>
<body>
<h1>Rohtak Gadget Store</h1>
<p id="cart" aria-live="polite">Cart: 0 items</p>
<div class="layout">
<main>
<h2>Deals of the day</h2>
<div class="grid">
<div data-component="product-card" data-product="speaker"></div>
<div data-component="product-card" data-product="charger"></div>
<div data-component="product-card" data-product="mouse"></div>
</div>
<section>
<h2>My account</h2>
<h3>Wishlist</h3>
<ul class="wishlist">
<li><div data-component="product-card" data-product="mouse" data-heading="4" data-button="Move to cart"></div></li>
</ul>
</section>
</main>
<aside aria-labelledby="recent">
<h2 id="recent">Recently viewed</h2>
<div data-component="product-card" data-product="charger" data-variant="compact"></div>
<div data-component="product-card" data-product="speaker" data-variant="compact"></div>
</aside>
</div>
<template id="product-card">
<article class="card">
<img src="" alt="" width="400" height="250">
<h3 class="name"></h3>
<p class="price"></p>
<button type="button"><span class="label"></span><span class="visually-hidden"></span></button>
</article>
</template>
<template id="price-tag">
<span class="price-tag"><strong class="now"></strong><s class="mrp"></s></span>
</template>
<script>
// Data lives in one place, as if it came from the server.
const products = {
speaker: { name: "Bluetooth speaker", price: 1299, mrp: 1599 },
charger: { name: "USB-C charger", price: 649 },
mouse: { name: "Wireless mouse", price: 499, mrp: 699 },
};
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
function renderPriceTag({ price, mrp }) {
const tag = document.querySelector("#price-tag").content.cloneNode(true);
tag.querySelector(".now").textContent = rupees.format(price);
if (mrp > price) tag.querySelector(".mrp").textContent = "MRP " + rupees.format(mrp);
else tag.querySelector(".mrp").remove();
return tag;
}
function renderProductCard(id, { heading = "3", variant = "full", button = "Add to cart" } = {}) {
const product = products[id];
const card = document.querySelector("#product-card").content.cloneNode(true);
const article = card.querySelector("article");
article.dataset.variant = variant;
card.querySelector("img").src = "https://course.ethicscomputer.in/assets/samples/landscape-400.svg";
const level = ["2", "3", "4", "5"].includes(heading) ? heading : "3";
const title = document.createElement("h" + level); // heading level is a prop
title.textContent = product.name;
card.querySelector(".name").replaceWith(title);
card.querySelector(".price").append(renderPriceTag(product)); // composition
const btn = card.querySelector("button");
if (variant === "compact") {
btn.remove();
} else {
btn.querySelector(".label").textContent = button;
btn.querySelector(".visually-hidden").textContent = ", " + product.name;
btn.addEventListener("click", () => {
article.dispatchEvent(new CustomEvent("add-to-cart", { bubbles: true, detail: { id } }));
});
}
return card;
}
for (const spot of document.querySelectorAll('[data-component="product-card"]')) {
const { product, ...options } = spot.dataset;
spot.replaceWith(renderProductCard(product, options));
}
let count = 0;
document.addEventListener("add-to-cart", (event) => {
count++;
document.querySelector("#cart").textContent =
`Cart: ${count} item(s). Last added: ${products[event.detail.id].name}`;
});
</script>
</body>
</html>You should see three full cards in the grid, two small cards in the sidebar and one card in the wishlist. Click "Add to cart" on the speaker: the line at the top changes to "Cart: 1 item(s). Last added: Bluetooth speaker". The wishlist button says "Move to cart" and sends the same event. In DevTools, the wishlist title is an <h4> and the others are <h3>. One template, one function, three looks.
Keeping components semantic and accessible
A component multiplies whatever you put in it, good or bad. Check these points:
- Use real elements inside. The card is an
<article>because it makes sense on its own. The button is a<button type="button">, not a clickable<div>. - Repeated buttons need unique names. A screen reader user who lists the buttons would hear "Add to cart" six times. The visually hidden product name makes each one "Add to cart, Bluetooth speaker". The ARIA Roles & Attributes lesson covers naming in detail.
- No ids inside the template. Every copy repeats them, and an
idmust be unique. Use classes, or generate an id with a counter if a<label for>oraria-labelledbyreally needs one. - Decide alt text once. Here the heading already names the product, so the photo uses
alt="". If the photo shows something the text does not, make the alt text a prop. - Insert data with
textContent. Product names may come from sellers.textContentkeeps them as plain text, never as HTML.
Common mistakes
- Extracting everything. A block used once does not need to be a component.
- Putting outer margins on the component. The parent controls spacing between components.
- Letting a component change things outside itself. Send an event; let the page decide.
- Copying the real data into every placeholder. Pass an id and keep data in one place.
- Forgetting defaults and missing props. A component should show something sensible, not "undefined" or "₹NaN".
Interview questions
1. What is a UI component, and why build pages from components?
A component is a reusable piece of interface with one job, its own markup and styles, and a defined set of inputs. Each piece is written, tested and fixed once, so pages stay consistent and fixes reach every instance.
2. How can you pass inputs to a component without a framework?
Use data-* attributes on a placeholder element and read them with dataset. A function clones a <template>, fills it from those values and replaces the placeholder. Real data can come from a JSON object keyed by an id, so the placeholder carries only the id and display options.
3. Why should a card component dispatch an event instead of updating the cart itself?
The card should not know where it is used. A custom event that bubbles lets each page decide what "add to cart" means, for example updating a count or moving an item out of a wishlist. This keeps the component reusable and easy to test.
4. How do you keep a reused component accessible?
Use semantic elements in the template, make the heading level an input, avoid fixed ids, and give repeated controls unique accessible names. A bug in a component repeats on every page, so fixes there pay off most.
5. What is composition?
Composition means building bigger components from smaller ones, such as a product card that uses a price tag component. The card calls the price tag's render function instead of copying its markup. Each piece stays small and can be changed in one place.
Key points
- A component is reusable UI with one job, its own markup and a small set of inputs (props).
- Extract a component when a pattern repeats, roughly on the third copy.
- A component controls its inside; the parent controls its size and outer spacing.
- In plain HTML, props travel as
data-*attributes; a function clones a<template>, fills it and replaces the placeholder. - Data goes in as props, and messages come out as bubbling custom events.
- Build big components by composing small ones, and keep every template semantic: real elements, context-based heading levels, unique button names and no fixed ids.
Exercise
Build a course-card component for a Pune coaching institute's website. Write its contract first (props: data-course, data-heading, data-variant). Keep the course data (title, duration in weeks, fee in rupees) in one JavaScript object. Use the card in two places: a grid of all courses under an <h2> (titles as <h3>), and a "Recommended for you" list inside a section that already has an <h3> (titles as <h4>, compact, no button). Each full card has an "Enquire" button whose accessible name includes the course title, and clicking it sends a bubbling enquire event that the page shows in a live status line.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Courses</title>
<style>
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 10px; }
.card { border: 1px solid #ccc; border-radius: 8px; padding: 10px; }
.card :is(h3, h4) { margin: 0 0 4px; font-size: 1rem; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
</style>
</head>
<body>
<h1>Pune Skills Academy</h1>
<p id="status" aria-live="polite"></p>
<h2>All courses</h2>
<div class="grid">
<div data-component="course-card" data-course="web"></div>
<div data-component="course-card" data-course="python"></div>
</div>
<section>
<h2>Your dashboard</h2>
<h3>Recommended for you</h3>
<ul>
<li><div data-component="course-card" data-course="python" data-heading="4" data-variant="compact"></div></li>
</ul>
</section>
<template id="course-card">
<article class="card">
<h3 class="title"></h3>
<p class="meta"></p>
<button type="button">Enquire<span class="visually-hidden"></span></button>
</article>
</template>
<script>
const courses = {
web: { title: "Web Design Basics", weeks: 8, fee: 12000 },
python: { title: "Python for Beginners", weeks: 10, fee: 15000 },
};
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
function renderCourseCard(id, { heading = "3", variant = "full" } = {}) {
const course = courses[id];
const card = document.querySelector("#course-card").content.cloneNode(true);
const article = card.querySelector("article");
const title = document.createElement("h" + (["3", "4"].includes(heading) ? heading : "3"));
title.textContent = course.title;
card.querySelector(".title").replaceWith(title);
card.querySelector(".meta").textContent = `${course.weeks} weeks, ${rupees.format(course.fee)}`;
const btn = card.querySelector("button");
if (variant === "compact") {
btn.remove();
} else {
btn.querySelector(".visually-hidden").textContent = ", " + course.title;
btn.addEventListener("click", () =>
article.dispatchEvent(new CustomEvent("enquire", { bubbles: true, detail: { id } })));
}
return card;
}
for (const spot of document.querySelectorAll('[data-component="course-card"]')) {
const { course, ...options } = spot.dataset;
spot.replaceWith(renderCourseCard(course, options));
}
document.addEventListener("enquire", (e) => {
document.querySelector("#status").textContent = `Thank you. We will call you about ${courses[e.detail.id].title}.`;
});
</script>
</body>
</html>The placeholders carry only the course id and display options, so fees change in one object. The heading level is a prop, the button name is unique per course, and the card reports clicks with an event instead of writing to the status line itself.
Quick Quiz
1. A product card appears under an <h2> on one page and under an <h3> on another. What is the best approach?
Heading level depends on where the card is placed, so it must be a prop, not fixed.
2. Who should control the space between two cards in a grid?
A component looks after its inside; the parent decides layout and spacing between children.
3. Why does the card send an add-to-cart event instead of changing the cart count itself?
Events keep the component unaware of its surroundings, so it works the same in a grid, a wishlist or a sidebar.
4. What is wrong with <button id="buy"> inside a template used ten times?
Every clone repeats the id; use classes or generate unique ids.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
