Overview
Constructs are OpenTUI’s declarative component system. They look like React or Solid components but work differently:- Not render functions - They’re constructors that create renderables
- No re-rendering - They build the tree once
- Composable - Create complex UIs from simple pieces
- Type-safe - Full TypeScript support with proper inference
Constructs vs Renderables
There are two ways to create UI elements in OpenTUI:Imperative (Renderables)
Declarative (Constructs)
Creating Constructs
Built-in Constructs
OpenTUI provides construct functions for all built-in renderables:Custom Constructs
Create reusable components with functional constructs:The VNode System
What is a VNode?
A VNode (Virtual Node) is a lightweight description of a renderable:Instantiation
Convert a VNode to a renderable usinginstantiate():
You rarely need to call
instantiate() manually - add() does it automatically when you pass a VNode.The h() Function
Under the hood, construct functions use h() to create VNodes:
h() directly for more control:
Method Chaining
VNodes support method chaining for renderable methods:- VNodes created from renderables are wrapped in a Proxy
- Method calls are captured and stored
- When instantiated, stored calls are replayed on the renderable
Property Assignment
You can also set properties:Delegation
Delegation lets you route API calls to nested children. This is crucial for composable components.The Problem
The Solution: delegate()
How Delegation Works
delegate()annotates the VNode with a mapping:{ focus: "username-input" }- When instantiated, the renderable is wrapped in a Proxy
- When
focus()is called, the proxy:- Finds the descendant with ID
"username-input" - Calls
focus()on that descendant instead - Caches the descendant for performance
- Finds the descendant with ID
Multiple Delegations
Composition Patterns
Container Components
Conditional Rendering
List Rendering
Slots Pattern
Complete Example
Here’s a full login form using constructs:Best Practices
Constructs are synchronous - Unlike React, there’s no reconciliation or diffing. The tree is built once.