A Page Component describes one block of the interface (a table, a header, a modal) and receives a root Locator from which it builds all inner locators. So it does not know its page, works on any page and can have several instances on one page without strict mode conflicts. The root is taken by role or test id, without nth, and a single-element block on one page needs no class.
Patterns · Page Component
A payments page has two identical tables. How many classes and how many copies of the locators are needed?
The payments page shows active and archived payments, and both lists are tables with the same rows, sorting and pagination. The first version: methods activeRow and archivedRow in PaymentsPage. A month later a table appears on the customers page, and the code is copied a second time. A Page Component removes those copies: a class describes one block of the interface, and the page creates as many instances as there are blocks on the screen. This lesson explains how it works, why the root is passed as a locator and where the limits of the pattern are.
How it works and why. The Page Object from the earlier lessons receives page and searches the whole page. A Page Component receives a Locator that points to the root of a block and builds every inner locator from it. Playwright supports this out of the box: Locator has the same getByRole, getByText and locator methods, and they search only inside the element found. Two properties follow. First: the component does not know where it sits, so it can be placed on any page. Second: a page can hold two instances with different roots, and they do not disturb each other.
One class, two instances
Figure 1. The page creates two DataTable objects with different roots. Each table sees only its own rows.
Where the knowledge about a table lives
Wrong
A method per table
activeRow and archivedRow differ by one line. A new table means a new copy, and a change in the row markup is fixed twice.
Right
One class, root from outside
Knowledge about rows, headers and sorting lives in DataTable. The page only says where the root is.
Figure 2. A component removes duplication, it does not add a layer.
Example: from two copies to one class. The starting point: the page itself knows how each table is built.
exportclassPaymentsPage {
constructor(privatereadonly page: Page) {}
activeRow(text: string) {
returnthis.page
.getByTestId('active-payments')
.getByRole('row')
.filter({ hasText: text });
}
// the same, only another root: a copy per tablearchivedRow(text: string) {
returnthis.page
.getByTestId('archived-payments')
.getByRole('row')
.filter({ hasText: text });
}
}
The logic is the same, only the root differs. If the way a row is found changes (say, by a cell rather than by row text), the edit is needed in several places, and in every page that has its own table. Now the same as a component. Four important places are marked.
The component receives a Locator, not page: it does not know where on the page it stands.
The rows locator is built from the root, so foreign tables do not get into the selection.
rowByText returns a locator, not a value: the test writes expect with auto-waiting itself.
The action is also inside the root: a click on another table’s header is impossible.
On the page, or right in the test, instances are created with different roots:
const active = newDataTable(page.getByTestId('active-payments'));
const archived = newDataTable(page.getByTestId('archived-payments'));
awaitexpect(active.rowByText('INV-42')).toBeVisible();
// the same invoice must not be in the archiveawaitexpect(archived.rowByText('INV-42')).toHaveCount(0);
The second assertion matters here: toHaveCount(0) confirms absence in this table, not on the whole page. Without a root the query would match both tables. If you try to find a row "just on the page", Playwright says so directly:
// without a root: rows of both tables matchawait page.getByRole('row').filter({ hasText: 'INV-42' }).click();
// strict mode violation: getByRole('row')// .filter({ hasText: 'INV-42' }) resolved to 2 elements
This is the same strict mode violation you meet when searching by label: a locator that found several elements cannot perform an action. A component root is a way to narrow the search without complex CSS selectors and without nth().
What to choose as a root. Best is a stable semantic anchor: getByRole('table', { name: 'Active payments' }), getByRole('dialog'), getByRole('banner') for a header, and if nothing fits, getByTestId. The root must point to one element. When a block appears later (a modal), it is not a problem: a locator is lazy, so the component can be created before the window opens and the search happens on the first action. A component may also be a table row: new OrderRow(table.rows.nth(2)) or a row found through filter, and then its methods work only within that row.
Limits and alternatives. A component is justified where a block repeats (on a page or between pages) or has its own behaviour: sorting, pagination, a date picker. A single-element block on one page needs no class: a locator field in the Page Object is shorter and reads the same. A component is not responsible for navigation and does not know the page it stands on. If it needs data from elsewhere (say, a user name to check the header), the test passes it. An alternative for many simple blocks: a helper function that takes a locator, though without state and a name such a function quickly grows into a set of scattered utilities.
Common mistakes.
A component takes page and searches globally: it works only while the page has one such block, and a second table breaks every check with strict mode.
The root is too wide (page.locator('body')) or points to several elements: the scoping benefit disappears and the error shows up in a random place.
The root is chosen with .first() or .nth(1): once a new table appears above, all tests quietly start working with another one.
A component stores search results (ElementHandle) instead of locators: after a re-render the reference goes stale.
Assertions with baked-in values inside a component: the same problems as in a Page Object (see the lesson on assertions).
Check yourself
A page has two tables and the component is created as new DataTable(page) with rows = page.getByRole('row'). What happens on rows.filter({ hasText: 'INV-42' }).click() if the invoice is in both tables?
Answer
The locator matches two rows, so click() throws a strict mode violation. The cause is that the search covers the whole page. The fix: the component receives the table's root Locator and builds rows from it, and then each instance sees only its own row.
A confirmation dialog appears only after a click. Can new ConfirmDialog(page.getByRole('dialog')) be created in the page constructor, before it opens?
Answer
Yes. A Locator is lazy: it only describes how to find an element and searches for nothing on creation. The search and waiting happen on the first action or assertion, so before the dialog opens the component is safe, and after that it finds the dialog by itself.
Related lessons: “What problem Page Object solves”, “Composition instead of inheritance”, “Assertions in a Page Object, god objects and inheritance”.
In an interview.Junior: I move a repeated block, such as a table or a header, into a separate class that receives a root locator and searches only inside it. So one class works on different pages. Middle/Senior: It is scoping through locator chaining: the component does not know the page and can appear several times on one, because each instance has its own root. I take the root by role or test id, without nth, and a lazy Locator lets me create the component before the block appears. For a single-element block on one page I do not make a class: it is an extra abstraction.
Composition instead of inheritance
Composition is more reliable than inheritance: a page declares the components it has, while a BasePage imposes its contents on every descendant. TypeScript will not notice that an inherited header is absent from the login page, so the error shows only at run time. The base class stays thin (page and goto), shared setup goes to fixtures, and chains deeper than two levels hide behind a page method.
Patterns · Page Component
The login page inherited BasePage with a header, but there is no header on it. What breaks first?
A team makes a BasePage with a header, a footer and a side menu because "they are everywhere". A week later a login page appears without any of them, and then a modal with its own table. Now the login class has three locators that are not in the DOM, and the modal code duplicates a table because the base does not have it. This lesson shows why "has-a" is more reliable than "is-a" and how to assemble a page from components.
How it works and why. Inheritance fixes the composition of a page when the class is declared: whatever the ancestor has, the descendant has too, and it cannot be removed. In TypeScript a class has only one ancestor, so a page that needs a header from one base class and a table from another cannot be assembled. Composition works the opposite way: the class declares the component fields it needs and creates them from root locators. The page decides its own composition, and components know nothing about their owners. A change in one does not spread through a hierarchy.
How a page gets a header
Wrong
Inherit from BasePage
The header exists in all descendants, even where there is none. Changing the base touches every page.
Right
Have a Header field
The page takes only what is on the screen. Components do not depend on pages and can be combined.
Figure 1. It is better to declare the page composition than to inherit it.
The composition of three pages
Figure 2. Each page assembles its own set. An empty LoginPage carries nothing extra, and SettingsPage nests a dialog.
Example: from BasePage to components. The starting point. A seemingly convenient base where one missing detail breaks the logic.
exportclassBasePage {
readonly header: Header;
readonly footer: Footer;
readonly menu: SideMenu;
constructor(protectedreadonly page: Page) {
this.header = newHeader(page.getByRole('banner'));
this.footer = newFooter(page.getByRole('contentinfo'));
this.menu = newSideMenu(page.getByRole('navigation'));
}
}
// the login page has neither a header nor a menuexportclassLoginPageextendsBasePage {}
The problem is not the class itself but the assumption that all pages are alike. A test on the login page may accidentally call login.header.openProfileMenu() and fail on a timeout, while the editor hint says the method exists. Now composition. Four important places are marked.
The field declares that the header is on this page. The login page does not have this field.
The header root is set in one place of the page and does not depend on others.
The dialog is a component too: it owns its buttons and may contain nested components of its own.
The modal is created only where it occurs.
The test matches what the user sees:
test('archive a payment from the list', async ({ page }) => {
const payments = newPaymentsPage(page);
await payments.goto();
await payments.header.openProfileMenu();
awaitexpect(payments.active.rowByText('INV-42')).toBeVisible();
});
The chain payments.header.openProfileMenu() reads as a description of the screen: page, its part, action. This form stays short while nesting is no deeper than two levels. Three or four dots in a row (page.a.b.c.d()) show that the test knows too much about the page structure; then add a method on the page that hides the path.
Limits and alternatives. A thin base is justified if it does only what is shared by all pages: it accepts page, has goto() and maybe path. Then it holds no components and has few reasons to change.
// a thin base: only what everyone really needsexport abstract classBasePage {
constructor(protectedreadonly page: Page) {}
abstract readonly path: string;
asyncgoto() {
awaitthis.page.goto(this.path);
}
}
The criterion is simple: does every descendant need every property of the base. If not, its place is in a component. For shared setup (login, data) Playwright fixtures fit better: they create the needed objects and clean them up after the test. Composition has a cost too: more files, and for a page with one locator field a component class is excessive. Do not create a component "for growth" if the block exists only on one page and is unlikely to repeat: extracting it later is easy, removing an unneeded abstraction is harder.
Common mistakes.
A "universal" BasePage with a header, a footer and a menu: the login page inherits what it does not have, and one changed locator in the base touches everyone.
A hierarchy of three or four levels: to find a method the reader walks through several files, and a change at the base level breaks every level below it.
A component receives a reference to the owning page and calls its methods: the dependency becomes circular and the component cannot be used on its own.
Long a.b.c.d chains in tests: the test knows too much about the internal structure. Add a method on the page.
Check yourself
The login page inherits BasePage, which has this.header. A developer writes login.header.openProfileMenu() and gets a timeout. Why did TypeScript not warn and what should change?
Answer
For TypeScript the header field exists because it is in the ancestor class. The compiler cannot see that the element is missing from the login page DOM, so the error appears only at run time. The fix: remove header from the base and declare it only on pages where it really exists.
What minimum responsibility is worth keeping in a page base class if you cannot avoid one?
Answer
Only what every page needs without exception: receiving page through the constructor and navigation (goto by path). Everything about individual interface blocks moves into components and is attached by composition.
Related lessons: “Page Component: what it is and why”, “Assertions in a Page Object, god objects and inheritance”, “SOLID in a test framework”, “Fixtures: DI built into Playwright Test”.
In an interview.Junior: I prefer composition: a page has component fields, such as a header or a table, and does not inherit them. Then each page takes only what it has. Middle/Senior: Inheritance fixes the composition at class declaration, and TypeScript has one ancestor, so a login page without a header already breaks BasePage. I assemble components from root locators and do not let them know their owners. I keep the base class thin: page and goto. Shared setup goes to fixtures, and chains deeper than two levels I hide behind a page method.