Course contentsShow
← React
Lesson 2046 of 2,39646. Testing React with RTLFree lesson

The container and baseElement

Understanding the DOM structure render creates and when you might need these rarely-used properties.

The container and baseElement

You'll learn what DOM structure render() actually creates and when you might need to access these low-level properties.

What render() Returns Under the Hood

When you call render(<MyComponent />), RTL doesn't just mount your component into thin air — it creates a real DOM structure. The function returns an object containing several properties, two of which expose this structure: container and baseElement.

The container is a <div> element that wraps your rendered component. Your component becomes a child of this container div.

The baseElement is the parent of the container — by default, this is the document.body. It's the root of the entire test DOM environment.

Why You Rarely Need These

In 99% of tests, you'll use the screen object to query elements, which searches within document.body automatically. You don't need direct DOM access.

However, these properties exist for edge cases:

const { container } = render(<MyComponent />);

// Edge case: testing a class on the wrapper itself
expect(container.firstChild).toHaveClass('my-root-class');

// Edge case: querySelector when RTL queries won't work
const element = container.querySelector('[data-weird-attribute]');

Analogy: It's like getting backstage access at a theater. Most audience members (tests) watch from their seats (use screen), but occasionally a technician needs to check the physical stage structure itself.

When Might You Use baseElement?

Very rarely — typically only when testing portals that render outside your component tree, or when you need to verify nothing leaked into the global document.

Key Takeaway: container and baseElement expose RTL's underlying DOM structure, but you'll almost always use screen instead — reach for these only when testing wrapper-level concerns or edge cases RTL's queries can't handle.