Skip to Content
vitus·labs
Attrs

Attrs

Immutable, chainable default-props factory for React components.

@vitus-labs/attrs is a composable attribute factory that lets you define default props, swap base components, attach HOCs, and add metadata through an immutable chaining API. Every method returns a new component instance — the original is never mutated.

What's new in 2.9

getDefaultAttrs() now includes .attrs(..., { priority: true }) values, resolved in the same order as at render time (priority attrs, then attrs). See .getDefaultAttrs().

Installation

npm install @vitus-labs/attrs

Peer dependencies: react >= 19, @vitus-labs/core

Try It Live

A real attrs() chain: priority attrs set the defaults, a callback .attrs() derives props from what you pass, and explicit props win. The JSON below is Button.getDefaultAttrs(props):

Quick Start

import attrs from '@vitus-labs/attrs'
import { Element } from '@vitus-labs/elements'

const Button = attrs({ name: 'Button', component: Element })
  .attrs({ tag: 'button', alignX: 'center', alignY: 'center' })

// Usage
<Button label="Click me" />

Factory Function

attrs({ name: string, component: ComponentType }): AttrsComponent
ParameterTypeRequiredDescription
namestringYesComponent display name (shows in React DevTools and data-attrs debug attribute)
componentElementTypeYesBase React component to wrap (class, function, or forwardRef)

Both parameters are validated in development — missing values throw descriptive errors with JSON-formatted details.

Immutability

Every chaining method creates a new component. Parent components are never affected by modifications to derived components:

const Base = attrs({ name: 'Base', component: Element })
  .attrs({ tag: 'div' })

const Card = Base.attrs({ tag: 'section' })
const Link = Base.attrs({ tag: 'a' })

// Base, Card, and Link are all independent components
// Modifying Card's chain has zero effect on Base or Link

This is achieved by cloneAndEnhance() internally — each chain method clones the configuration, creates a fresh component, and returns the new instance.

Props Merge Order

When a component renders, props are resolved in this order (last wins):

1. Priority attrs  (lowest precedence — resolved first)
2. Normal attrs    (chain order, later .attrs() calls override earlier)
3. Explicit props  (highest precedence — what you pass to <Component />)

How It Works at Runtime

  1. Strip undefined props — removeUndefinedProps() removes keys with undefined values from explicit props so they don't shadow defaults
  2. Resolve priority attrs — Call all priority attrs callbacks with the filtered explicit props
  3. Resolve normal attrs — Call all normal attrs callbacks with { ...priorityAttrs, ...filteredProps }
  4. Merge — { ...priorityAttrs, ...normalAttrs, ...filteredProps }

Undefined vs Null Behavior

ValueBehavior
undefinedStripped before merging — does NOT override defaults
nullPreserved — explicitly overrides defaults
false / 0 / ''Preserved — explicitly overrides defaults
const Button = attrs({ name: 'Button', component: Element })
  .attrs({ label: 'Default' })

<Button label={undefined} />   // Renders "Default" (undefined stripped)
<Button label={null} />        // Renders null (null is explicit)
<Button label="" />            // Renders "" (empty string is explicit)
<Button label="Custom" />      // Renders "Custom"

Type Extension

Use generics to extend the component's prop types through the chain:

const Button = attrs({ name: 'Button', component: Element })
  .attrs<{ variant: 'primary' | 'secondary' }>({
    variant: 'primary',
    tag: 'button',
  })
  .attrs<{ size?: 'sm' | 'md' | 'lg' }>({})

// TypeScript now knows about variant and size
<Button variant="secondary" size="lg" label="Submit" />

Types are accumulated via MergeTypes<[OA, EA]> — a tuple merge that works like Object.assign for types, with later types overriding earlier ones.

Component Variants

Create multiple variants from a shared base:

const BaseButton = attrs({ name: 'BaseButton', component: Element })
  .attrs({ tag: 'button', alignX: 'center', alignY: 'center' })

const PrimaryButton = BaseButton
  .config({ name: 'PrimaryButton' })
  .attrs({ className: 'btn-primary' })

const SecondaryButton = BaseButton
  .config({ name: 'SecondaryButton' })
  .attrs({ className: 'btn-secondary' })

const IconButton = BaseButton
  .config({ name: 'IconButton' })
  .attrs((props) => ({
    'aria-label': props.label || 'icon button',
  }))

Type Guard

Identify attrs components at runtime:

import { isAttrsComponent } from '@vitus-labs/attrs'

isAttrsComponent(Button)      // true
isAttrsComponent(PlainDiv)    // false
isAttrsComponent(null)        // false

The check verifies the component is a non-null object with an own IS_ATTRS property (via Object.hasOwn).

Component Architecture

Every attrs component has this internal layer structure:

Consumer Props + Ref
    ↓
attrsHoc (resolve priority/normal attrs, merge with explicit props)
    ↓
User-Composed HOCs (in reverse declaration order)
    ↓
EnhancedComponent (memo — merges refs, filters props, adds data-attrs in dev)
    ↓
Original Component

Ref Forwarding

Refs are forwarded through the entire HOC chain:

const Button = attrs({ name: 'Button', component: Element })
  .compose({ withFeature: someHoc })

const ref = useRef(null)
<Button ref={ref}>Click</Button>
// ref.current points to the DOM node through all HOC layers

The system manages two ref sources internally:

  • $attrsRef — The consumer's ref (from the outermost attrsHoc)
  • ref — Intermediate HOC refs (from compose wrappers)

Both are merged into a single callback ref that React re-invokes on every attach/detach, so all ref sources always point to the live DOM node (even after a host remount, e.g. a tag change) without any useImperativeHandle indirection.

Memoization

The innermost EnhancedComponent is wrapped in memo(), and attrsHoc stabilizes its output with useStableValue + useMemo. A parent re-render with content-equal props therefore bails at the memo boundary instead of re-rendering the wrapped component. Components with no .attrs() configured take a fast path that skips the merge entirely.

Debug Mode

In development (process.env.NODE_ENV !== 'production'), attrs components add a data-attrs attribute to rendered elements:

<!-- Dev output -->
<div data-attrs="MyButton" ...>

This helps identify which attrs component rendered a given DOM node in browser DevTools.

All Exports

import attrs, { isAttrsComponent } from '@vitus-labs/attrs'

import type {
  AttrsComponent,
  Attrs,
  AttrsComponentType,
  ConfigAttrs,
  AttrsCb,
  GenericHoc,
  ComposeParam,
  IsAttrsComponent,
  ElementType,
  TObj,
} from '@vitus-labs/attrs'
ExportTypeDescription
attrsFunction (default)Factory to create attrs-enhanced components
isAttrsComponentFunctionRuntime type guard
AttrsComponentTypeFull component type with chain methods and statics
AttrsTypeFactory function signature
AttrsComponentTypeTypeComponent type returned by factory
ConfigAttrsTypeParameters for .config() method
AttrsCbTypeCallback form of .attrs(): (props) => Partial<Props>
GenericHocTypeHOC signature: (component) => component
ComposeParamTypeParameters for .compose() method
IsAttrsComponentTypeType guard signature
ElementTypeTypeComponent type accepted as component
TObjTypeRecord<string, unknown> helper used by generics
Edit on GitHub

Last updated on

On this page