Components and Props
DriftJS encourages building complex user interfaces from small, reusable components.
1. Importing and Using Components
Components are imported using ESM import statements inside <script>:
<!-- Parent.drift -->
<script>
import Card from './Card.drift';
import Button from './Button.drift';
let user = { name: 'Grace Hopper', rank: 'Rear Admiral' };
</script>
<main class="page">
<Card title={user.name} subtitle={user.rank}>
<p>Pioneer of computer programming and compiler development.</p>
<Button variant="primary">View Profile</Button>
</Card>
</main>
By convention, tags starting with an uppercase letter (<Card>, <Button>) are treated as component tags by the compiler.
2. Passing Props
Static Props
Pass string literals directly:
<Button variant="secondary" size="large" fullWidth>Click</Button>
Dynamic Props
Pass reactive expressions using curly braces {}:
<Avatar src={user.avatarUrl} alt={user.name} size={size * 2} />
Try a live component that receives and reacts to props-style values:
✦ Edit name, rank, or cycle the variant — props-driven reactive UI in action.
3. Receiving Props in Child Components
In the child component, attributes passed by the caller are exposed on the props object:
<!-- Card.drift -->
<script>
// props are injected into component scope
</script>
<div class="card-container">
<div class="card-header">
<h3>{props.title}</h3>
@if props.subtitle {
<span class="subtitle">{props.subtitle}</span>
}
</div>
<div class="card-body">
{children}
</div>
</div>
Slot Content Projection with Children
When a component wraps child elements:
<Modal isOpen={showModal}>
<h2>Confirm Deletion</h2>
<p>Are you sure you want to proceed?</p>
</Modal>
The children are compiled into an isolated sub-module passed to the child component under children. In the child component, simply place {children} where you want the projected markup to render:
<!-- Modal.drift -->
<div class="modal-backdrop">
<div class="modal-dialog">
<div class="modal-content">
{children}
</div>
</div>
</div>
Virtual Machine Execution with Mount Component
Under the hood:
- The compiler emits
MOUNT_COMPONENT dstReg, tagIdx, propsSpecIdx. - The VM creates a child VM instance (
new DriftClientVM()ornew DriftServerVM()). - The child VM inherits the parent's prototype scope via
Object.create(parentScope), bindingpropsandchildren. - The mounted root node or fragment is stored directly in
dstRegand appended into the parent tree.