COMPONENT-DRIVEN POM & UI WIDGET COMPOSITION

Master modular UI modeling in Playwright with Python: moving beyond monolithic page objects to reusable Component Object Models (COM), parent locator scoping via Locator root chaining, data table abstractions, nested modals, composite widgets, and scalable test architecture.

🧩 The Evolution: From Monolithic Pages to Modular Components

Modern frontend frameworks (React, Angular, Vue, Web Components) build interfaces out of small, self-contained widgets: dynamic data tables, date-pickers, confirmation modals, navigation headers, and cart drawers. In traditional Page Object Model (POM) designs, duplicating selectors and interaction methods across multiple page classes creates large, 1,000-line monolithic files that are difficult to maintain. Component-Driven POM (also known as the Component Object Model or COM) addresses this directly. In Playwright with Python, components are structured by passing a parent root: Locator into a lightweight Python class. All child queries inside the component chain off this root (self.root.locator(...)). This ensures strict DOM encapsulation, supports infinite widget reuse, and enables composition over rigid inheritance hierarchies.

1. Monolithic POM vs. Component-Driven Architecture
Monolithic page objects accumulate hundreds of selectors and methods for every recurring widget on a screen. Component-driven design promotes small, specialized classes composed together within a parent page.
Architectural Composition Topology
MONOLITHIC POM (Anti-Pattern: Huge Classes, Code Duplication):
┌─────────────────────────────────────────────────────────────────────────────┐
│ CustomerPage (pages/customers.py - 1,200 lines)                             │
│  * Header selectors, Search input, Sorting icons, Table rows, Pagination,   │
│    Export button, Delete modal, Toast alerts, Sidebar links...              │
└─────────────────────────────────────────────────────────────────────────────┘
  ❌ OrdersPage duplicates table, modal, and header selectors all over again!

COMPONENT-DRIVEN POM (Idiomatic: Modular, Encapsulated & Composable):
┌─────────────────────────────────────────────────────────────────────────────┐
│ CustomerPage (pages/customers.py - 60 lines)                                │
│                                                                             │
│  ├── self.nav_bar     = NavigationBar(page.locator("header.main-header"))   │
│  ├── self.data_table  = DataTableComponent(page.locator("#customer-grid"))  │
│  ├── self.pagination  = PaginationWidget(page.locator(".pagination-footer"))│
│  └── self.modal       = ConfirmationModal(page.locator("#confirm-dialog"))  │
└─────────────────────────────────────────────────────────────────────────────┘
  ✅ OrdersPage reuses the EXACT same DataTable, Modal, and Navigation classes!
Architectural Advantage: Update table sorting logic or modal confirmation behavior in one component class, and every test suite consuming that widget immediately benefits.
Real-Time Example 1: Foundational BaseComponent & Root Locator Scoping
Establish a common BaseComponent class taking a root: Locator. All internal queries are strictly scoped to this container, ensuring zero selector collisions with elements elsewhere on the page.
Python (components/base_component.py)
from playwright.sync_api import Locator, Page

class BaseComponent:
    """Base class for all modular UI component widgets."""

    def __init__(self, root: Locator):
        # The parent root container isolates all child element searches
        self.root: Locator = root
        self.page: Page = root.page

    def is_visible(self) -> bool:
        """Checks if the component container is currently rendered."""
        return self.root.is_visible()

    def wait_for_displayed(self, timeout: float = 5000) -> None:
        """Waits for the widget container to reach visible state."""
        self.root.wait_for(state="visible", timeout=timeout)
Scoping Standard: Root chaining guarantees that child locators only resolve inside self.root, preventing duplicate matches from other widgets on the screen.
Real-Time Example 2: Reusable Modal Dialog Component
Encapsulate confirmation and warning dialogs. The component manages the modal title, body message, proceed button, and cancel actions within its container.
Python (components/modal_dialog.py)
from playwright.sync_api import Locator, sync_playwright, expect

class ModalDialogComponent(BaseComponent):
    """Reusable modal dialog component for confirmations and alerts."""

    def __init__(self, root: Locator):
        super().__init__(root)
        self.title: Locator = self.root.locator(".modal-title, h3")
        self.body_text: Locator = self.root.locator(".modal-body, p")
        self.confirm_button: Locator = self.root.locator("button.btn-confirm")
        self.cancel_button: Locator = self.root.locator("button.btn-cancel")
        self.close_icon: Locator = self.root.locator("button.close-icon")

    def confirm(self) -> None:
        self.confirm_button.click()

    def cancel(self) -> None:
        self.cancel_button.click()

    def get_title(self) -> str:
        return self.title.inner_text().strip()

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
Active
""") # Instantiate modal component targeting the container modal = ModalDialogComponent(page.locator("#popup")) page.locator("#open-btn").click() modal.wait_for_displayed() expect(modal.title).to_have_text("Delete Project Record") print(f"Modal opened: '{modal.get_title()}'") modal.confirm() expect(page.locator("#status")).to_have_text("RECORD_DELETED") print("Action confirmed through ModalDialogComponent!") browser.close()
Output: Modal opened: 'Delete Project Record' Action confirmed through ModalDialogComponent!
Real-Time Example 3: Generic Data Table Component with Row & Column Lookup
Build an enterprise DataTableComponent capable of extracting cell values, locating specific rows by column criteria, clicking row-level actions, and computing row counts.
Python (components/data_table.py)
from typing import List
from playwright.sync_api import Locator, sync_playwright, expect

class DataTableComponent(BaseComponent):
    """Dynamic table component supporting row queries and action dispatching."""

    def __init__(self, root: Locator):
        super().__init__(root)
        self.headers: Locator = self.root.locator("thead th")
        self.rows: Locator = self.root.locator("tbody tr")

    def get_row_count(self) -> int:
        return self.rows.count()

    def get_row_by_text(self, text: str) -> Locator:
        """Finds row containing specific text identifier."""
        return self.rows.filter(has_text=text)

    def click_action_in_row(self, row_text: str, button_text: str) -> None:
        """Finds target row and triggers action button inside that specific row."""
        target_row = self.get_row_by_text(row_text)
        target_row.locator("button", has_text=button_text).click()

    def get_column_values(self, col_index: int) -> List[str]:
        """Extracts text content across an entire column by 1-based index."""
        cells = self.rows.locator(f"td:nth-child({col_index})")
        return [cells.nth(i).inner_text().strip() for i in range(cells.count())]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
Order IDCustomerStatusActions
ORD-101Pooja PatilCompleted
ORD-102Aarav SharmaPending
ORD-103Rahul VermaCompleted
""") table = DataTableComponent(page.locator("#orders-grid")) print(f"Total Rows Counted: {table.get_row_count()}") order_ids = table.get_column_values(1) print(f"Extracted Order IDs: {order_ids}") # Approve pending order in row 2 table.click_action_in_row("ORD-102", "Approve") approved_row = table.get_row_by_text("ORD-102") expect(approved_row.locator("button")).to_have_text("Approved") print("Action clicked inside targeted row via DataTableComponent!") browser.close()
Output: Total Rows Counted: 3 Extracted Order IDs: ['ORD-101', 'ORD-102', 'ORD-103'] Action clicked inside targeted row via DataTableComponent!
Real-Time Example 4: Composing Multiple Components Inside a Parent Page
Construct a comprehensive UsersDashboardPage by composing individual NavigationBar, DataTableComponent, and ModalDialogComponent widgets.
Python (pages/users_dashboard_page.py)
from playwright.sync_api import Page, sync_playwright, expect

class NavigationBar(BaseComponent):
    def __init__(self, root):
        super().__init__(root)
        self.brand_logo = self.root.locator(".brand-title")
        self.user_menu = self.root.locator(".user-profile")

class UsersDashboardPage:
    """Composite Page Object assembling modular component objects."""

    def __init__(self, page: Page):
        self.page = page
        # Components composed together
        self.navbar = NavigationBar(page.locator("header.top-nav"))
        self.user_table = DataTableComponent(page.locator("table#users-table"))
        self.delete_modal = ModalDialogComponent(page.locator("div#delete-modal"))

    def delete_user_by_name(self, name: str) -> None:
        """High-level page workflow coordinating multiple components."""
        self.user_table.click_action_in_row(name, "Delete")
        self.delete_modal.wait_for_displayed()
        self.delete_modal.confirm()

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
Nikita-Infotech Portal
Pooja Patil
Idle
""") dashboard = UsersDashboardPage(page) expect(dashboard.navbar.brand_logo).to_have_text("Nikita-Infotech Portal") dashboard.delete_user_by_name("Pooja Patil") expect(page.locator("#status")).to_have_text("PURGED") print("Multi-component orchestration completed with clean separation of concerns!") browser.close()
Output: Multi-component orchestration completed with clean separation of concerns!
Real-Time Example 5: Handling Repeating Card Lists via Component Collections
E-commerce storefronts and social dashboards display repeated card items. Wrap repeating DOM elements in a factory pattern returning a list of discrete ProductCardComponent objects.
Python (Repeating Card List Components)
from typing import List
from playwright.sync_api import Locator, Page, sync_playwright, expect

class ProductCardComponent(BaseComponent):
    """Component wrapping a single item card in a catalog grid."""

    def __init__(self, root: Locator):
        super().__init__(root)
        self.title: Locator = self.root.locator(".item-title")
        self.price: Locator = self.root.locator(".item-price")
        self.add_button: Locator = self.root.locator("button.add-to-cart")

    def add_to_cart(self) -> None:
        self.add_button.click()

class CatalogPage:
    def __init__(self, page: Page):
        self.page = page
        self.card_locators: Locator = page.locator(".catalog-grid .product-card")

    def get_cards(self) -> List[ProductCardComponent]:
        """Dynamically wraps each matched card locator into a Component instance."""
        count = self.card_locators.count()
        return [ProductCardComponent(self.card_locators.nth(i)) for i in range(count)]

    def get_card_by_title(self, title: str) -> ProductCardComponent:
        matching_root = self.card_locators.filter(has=self.page.locator(".item-title", has_text=title))
        return ProductCardComponent(matching_root)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Optic Sensor Node

₹ 4,500

Industrial Gateway

₹ 8,200
""") catalog = CatalogPage(page) all_items = catalog.get_cards() print(f"Total Cards Discovered in Catalog: {len(all_items)}") target_card = catalog.get_card_by_title("Industrial Gateway") expect(target_card.price).to_have_text("₹ 8,200") target_card.add_to_cart() expect(target_card.add_button).to_have_text("Added") print(f"Added item to cart via targeted card component: '{target_card.title.inner_text()}'") browser.close()
Output: Total Cards Discovered in Catalog: 2 Added item to cart via targeted card component: 'Industrial Gateway'
Real-Time Example 6: Nested Components (Components Inside Components)
Build multi-level component trees. A complex widget (such as a DataTableComponent) can embed sub-components (such as a PaginationComponent or RowActionMenu).
Python (Nested Component Hierarchies)
from playwright.sync_api import Locator, sync_playwright, expect

class PaginationComponent(BaseComponent):
    """Sub-component managing page stepping."""
    def __init__(self, root: Locator):
        super().__init__(root)
        self.next_page_btn = self.root.locator("button.btn-next")
        self.page_number = self.root.locator(".active-page")

    def go_next(self) -> None:
        self.next_page_btn.click()

class AdvancedGridComponent(BaseComponent):
    """Parent component nesting both table rows and pagination sub-component."""
    def __init__(self, root: Locator):
        super().__init__(root)
        self.rows = self.root.locator("tbody tr")
        # Nested component scoped inside parent root
        self.pagination = PaginationComponent(self.root.locator(".table-pagination"))

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
Row 1
Page 1
""") grid = AdvancedGridComponent(page.locator("#analytics-grid-wrapper")) expect(grid.pagination.page_number).to_have_text("Page 1") grid.pagination.go_next() expect(grid.pagination.page_number).to_have_text("Page 2") print(f"Nested pagination component advanced to: '{grid.pagination.page_number.inner_text()}'") browser.close()
Output: Nested pagination component advanced to: 'Page 2'
Real-Time Example 7: Form & Input Group Component Wrappers
Wrap custom enterprise inputs (e.g., custom dropdowns, comboboxes, currency inputs with validation labels) into an InputGroupComponent that manages value setting and validation message inspection.
Python (Custom Form Input Group Component)
from playwright.sync_api import Locator, sync_playwright, expect

class FormFieldComponent(BaseComponent):
    """Component managing label, input field, and inline validation text."""

    def __init__(self, root: Locator):
        super().__init__(root)
        self.label: Locator = self.root.locator("label")
        self.input_field: Locator = self.root.locator("input, select, textarea")
        self.error_text: Locator = self.root.locator(".field-error, .invalid-feedback")

    def fill_value(self, value: str) -> None:
        self.input_field.fill(value)

    def get_error(self) -> str:
        return self.error_text.inner_text().strip()

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
Invalid enterprise domain
""") email_group = FormFieldComponent(page.locator("#email-field-group")) print(f"Field Label Name: '{email_group.label.inner_text()}'") email_group.fill_value("pooja@nikita-infotech.com") expect(email_group.error_text).to_have_text("Invalid enterprise domain") print(f"Captured Inline Validation Error: '{email_group.get_error()}'") browser.close()
Output: Field Label Name: 'Official Work Email' Captured Inline Validation Error: 'Invalid enterprise domain'
Real-Time Example 8: Pytest Fixtures for Component Dependency Injection
Define granular Pytest fixtures yielding component instances directly into test functions, enabling clean widget-level tests without boilerplate page setups.
Python (conftest.py Component Fixtures)
# content of conftest.py
import pytest
from playwright.sync_api import Page

@pytest.fixture
def confirmation_modal(page: Page) -> ModalDialogComponent:
    """Fixture providing ready-to-use modal dialog component."""
    return ModalDialogComponent(page.locator("#global-confirm-dialog"))

@pytest.fixture
def main_navigation(page: Page) -> NavigationBar:
    """Fixture providing global header navigation component."""
    return NavigationBar(page.locator("header.main-nav"))

# content of tests/test_modal_interaction.py
def test_modal_cancellation(page: Page, confirmation_modal: ModalDialogComponent):
    page.set_content("""
        
        
    """)
    page.locator("#open").click()

    # Direct component assertion and interaction via fixture!
    confirmation_modal.wait_for_displayed()
    assert confirmation_modal.get_title() == "Discard Draft?"
    confirmation_modal.cancel()
    assert not confirmation_modal.is_visible()
    print("Component fixture test passed cleanly!")
Output: Component fixture test passed cleanly! PASSED tests/test_modal_interaction.py::test_modal_cancellation
Real-Time Example 9: Component-Driven POM Reference & Design Matrix
A comprehensive reference summary contrasting Page Object and Component Object design principles, parameter signatures, and structural patterns.
Component Object Model (COM) Reference Matrix
COMPONENT OBJECT MODEL (COM) ARCHITECTURAL MATRIX:
┌──────────────────────────────┬──────────────────────────────────────────┬──────────────────────────────────────────┐
│ Architectural Dimension      │ Page Object Model (POM)                  │ Component Object Model (COM)             │
├──────────────────────────────┼──────────────────────────────────────────┼──────────────────────────────────────────┤
│ Scope of Representation      │ Entire browser screen / URL route        │ Discrete, reusable DOM widget            │
│ Constructor Signature        │ __init__(self, page: Page)               │ __init__(self, root: Locator)            │
│ Locator Chaining Paradigm    │ self.page.locator("...")                 │ self.root.locator("...")                 │
│ Code Reusability             │ Bound to specific page URL lifecycle     │ Embedded across unlimited pages/views    │
│ Relationship Model           │ Inheritance (BasePage -> LoginPage)      │ Composition (Page has-a Component)       │
│ Common Implementations       │ LoginPage, DashboardPage, CheckoutPage   │ DataTable, Modal, NavHeader, DatePicker  │
│ DOM Collision Prevention     │ Prone to global CSS class name clashes   │ Strict isolation inside self.root scope  │
└──────────────────────────────┴──────────────────────────────────────────┴──────────────────────────────────────────┘
Engineering Best Practice: Favor composition over inheritance. Pass a root Locator into your component constructors, chain all internal queries from self.root, and compose those components as attributes inside your page objects.