— Layout & primitives · @vitus-labs/attrs

Defaults, HOCs and statics. One chain.

Wrap any component once and grow it with .attrs(), .config(), .compose() and .statics(). Every call returns a new component, so a variant never leaks back into its base. Default props merge under the props you pass, prop types accumulate through the chain, and refs reach the DOM through every HOC.

@vitus-labs/attrsv2.9.1 · MIT
npm i @vitus-labs/attrs @vitus-labs/core
chain methods, each returns a new component
4
merge layers: priority, attrs, props
3
leaf re-renders on content-equal updates
0

— Why attrs

Variants without wrapper sprawl.

01

Forks never touch the parent

Base.attrs({ tag: 'section' }) clones the configuration and builds a fresh component. Base and every other variant stay exactly as they were, so a design system can derive dozens of components from one base without order-of-import surprises.

02

Defaults that stay defaults

Props resolve as priority attrs, then attrs, then what you pass: last wins. undefined props are stripped first, so <Button tag={undefined}> keeps the default instead of erasing it. Attrs callbacks receive the incoming props, so defaults can be derived from them.

03

HOCs you can name and remove

.compose({ withTracking }) registers HOCs by key. A later .compose({ withTracking: null }) removes one from a single variant. Refs pass through every layer to the rendered node through one merged callback ref.

04

Cheap when nothing changed

Incoming props are stabilized by deep equality and the inner component is memoized, so a parent re-rendering with equal props renders nothing below it. Components with no .attrs() skip the merge work entirely.

— Before / after

Same button family. No wrapper pile.

A button with defaults, a link variant, a tracking HOC and a static for tooling. On the left each variant is another hand-written wrapper; on the right each is one chained call.

beforeHand-rolled wrappers
Button.tsx
import { Element } from '@vitus-labs/elements'
import { withTracking } from './tracking'

const BaseButton = ({ ref, ...props }) => (
  <Element tag="button" alignX="center" {...props} ref={ref} />
)

export const Button = withTracking(BaseButton)
Button.displayName = 'Button'
Button.category = 'action'

const BaseLink = (props) => <BaseButton tag="a" {...props} />
export const LinkButton = withTracking(BaseLink)
LinkButton.displayName = 'LinkButton'
LinkButton.category = 'action'

// an untracked variant? write a third wrapper

Every variant re-spreads props, re-applies the HOC, re-sets displayName and re-attaches statics by hand.

after@vitus-labs/attrs
Button.tsx
import { attrs } from '@vitus-labs/attrs'
import { Element } from '@vitus-labs/elements'
import { withTracking } from './tracking'

export const Button = attrs({ name: 'Button', component: Element })
  .attrs({ tag: 'button', alignX: 'center' })
  .compose({ withTracking })
  .statics({ category: 'action' })

export const LinkButton = Button
  .config({ name: 'LinkButton' })
  .attrs({ tag: 'a' })

export const QuietButton = Button.compose({ withTracking: null })

Button.meta.category // 'action'

Each variant is a fork of the chain. HOCs are keyed, statics live on .meta, and the original stays untouched.

— Features

What one chain carries.

  • .attrs(object | fn)

    default props, static or computed from the incoming props; later calls override earlier ones

  • { priority: true }

    a baseline layer resolved first, which normal attrs and explicit props can both override

  • { filter: [...] }

    strip internal props before they reach the wrapped component, without writing a destructure

  • .config()

    rename the component (displayName) or swap the component it wraps

  • .compose({ name: hoc })

    keyed HOCs; set a key to null or false to drop it from one variant

  • .statics() → .meta

    metadata for tooling and docs, merged across the chain and read from Component.meta

  • getDefaultAttrs(props)

    the defaults a render would compute, resolved in the same order as the HOC

  • Typed accumulation

    .attrs<{ variant: 'a' | 'b' }>() merges variant into the component's props for every later step

  • $$types

    type-only handles for the final, original and extended props of any attrs component

  • Ref merging

    one callback ref feeds both the consumer's ref and any HOC's ref, and follows host remounts

  • isAttrsComponent

    a runtime guard that checks for the IS_ATTRS marker on the component itself

  • data-attrs

    in development every rendered node names the attrs component that produced it

— API

One factory. Four chain methods.

Every name links to its reference in the docs.

— Honest limits

When a plain wrapper is enough.

Where it isn't the right fit, and what to reach for instead.

  • It doesn't style anything

    Attrs manages props, HOCs and metadata. For variants that change CSS, use rocketstyle, which has the same chain plus dimensions and themes, or put a styler component underneath.

  • Inline functions defeat the memo

    Incoming props are compared by deep equality on every render. Functions are compared by reference, so a fresh inline onClick each render re-renders the leaf. Large data props cost a full walk. Hoist or memoize callbacks you pass.

  • Swapping the component keeps the defaults

    .config({ component }) keeps the existing .attrs() chain, so defaults written for the old component's props reach the new one. Fork from a base that doesn't carry them, or use filter.

  • Missing name or component is a dev-only error

    attrs() throws when name or component is missing, but only outside production. A production build renders whatever it was given.

— Recipes

Copy, paste, ship.

01

Derive props from props

A callback .attrs() sees the incoming props merged over the priority layer. Explicit props still win, and undefined ones don't erase a default.

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

export const SaveButton = attrs({ name: 'SaveButton', component: Element })
  .attrs({ tag: 'button', type: 'button', label: 'Save' }, { priority: true })
  .attrs<{ saving?: boolean }>(({ saving }) => ({
    disabled: saving,
    'aria-busy': saving,
    ...(saving && { label: 'Saving…' }),
  }), { filter: ['saving'] })

// <SaveButton saving />           → disabled, aria-busy, "Saving…"
// <SaveButton label="Publish" />   → explicit label wins
02

A family from one base

Each fork is independent. Change Link and neither Base nor Card notices.

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

export const Card = Base.config({ name: 'Card' }).attrs({ tag: 'article' })
export const Link = Base.config({ name: 'Link' }).attrs({ tag: 'a', block: false })

Base.getDefaultAttrs({}) // { tag: 'div', block: true }
Link.getDefaultAttrs({}) // { tag: 'a', block: false }
03

HOCs by name

The last-declared HOC wraps outermost. Remove one from a single variant by setting its key to null.

Field.tsx
import { attrs } from '@vitus-labs/attrs'
import { Input } from './Input'
import { withLabel, withValidation } from './hocs'

export const Field = attrs({ name: 'Field', component: Input })
  .compose({ withValidation, withLabel })
// render: attrsHoc → withLabel → withValidation → Input

export const BareField = Field.compose({ withLabel: null })
04

Read the accumulated types

Type-only handles expose what the chain has built, so wrappers and tooling never retype props.

types.ts
const Tag = attrs({ name: 'Tag', component: Element })
  .attrs<{ tone: 'neutral' | 'danger' }>({ tone: 'neutral' })

type TagProps = typeof Tag.$$types          // Element props & { tone }
type TagOwn = typeof Tag.$$extendedTypes    // { tone: 'neutral' | 'danger' }

— FAQ

Questions, answered.

How is it different from styled-components' `.attrs()`?

It works on any React component, not only styled ones, and adds .config(), .compose() and .statics() around it. Defaults sit under the props you pass, and every call returns a new component instead of extending one in place.

Do priority attrs beat explicit props?

No. Priority attrs are the lowest layer: they're resolved first so that normal attrs callbacks can see them, and both normal attrs and explicit props override them.

What does `.config({ DEBUG: true })` do?

The option is typed but has no runtime effect. The data-attrs attribute is added in every non-production build, whether or not you set it.

How does it relate to rocketstyle?

Rocketstyle components expose the same .attrs(), .config(), .compose() and .statics() chain and add dimensions, themes and light/dark on top. Use attrs when you only need props and HOCs.

— @vitus-labs/attrs

Write the base once. Fork the rest.

npm i @vitus-labs/attrs @vitus-labs/core
Sources · 31 claims, each traced to v2.9.1 code or docs
  1. Every chain call clones the configuration and returns a new component; the original is never mutatedui-system:packages/attrs/src/attrs.tsx
  2. Chain methods attrs, config, compose, statics (plus getDefaultAttrs)ui-system:packages/attrs/src/attrs.tsx
  3. Merge order: priority attrs < attrs < explicit props (last wins)ui-system:packages/attrs/src/hoc/attrsHoc.tsx
  4. Attrs callbacks receive priority attrs merged under the incoming propsui-system:packages/attrs/src/hoc/attrsHoc.tsx
  5. undefined props are stripped so they don't override defaults; null is keptui-system:packages/attrs/src/utils/attrs.ts
  6. Later .attrs() calls override earlier onesui-system:packages/attrs/src/utils/attrs.ts
  7. filter option strips props before they reach the wrapped componentui-system:packages/attrs/src/attrs.tsx
  8. .config() renames or swaps the component; existing attrs chain is carried overui-system:packages/attrs/src/attrs.tsx
  9. compose HOCs are keyed; null / undefined / false removes oneui-system:packages/attrs/src/types/hoc.ts
  10. Last-declared HOC runs first (outermost user wrapper)ui-system:packages/attrs/src/__tests__/attrs.test.tsx
  11. attrsHoc is always the outermost HOCui-system:packages/attrs/src/hoc/attrsHoc.tsx
  12. statics are stored on Component.metaui-system:packages/attrs/src/utils/statics.ts
  13. getDefaultAttrs(props) mirrors the HOC merge order including priority attrsui-system:packages/attrs/src/attrs.tsx
  14. Each .attrs<P>() merges P into the component's props (MergeTypes)npm:@vitus-labs/attrs/lib/index.d.ts
  15. Type-only $$types / $$originTypes / $$extendedTypesui-system:packages/attrs/src/types/AttrsComponent.ts
  16. One merged callback ref feeds consumer ref and HOC ref, tracks host remountsui-system:packages/attrs/src/hooks/useRef.ts
  17. isAttrsComponent checks for an own IS_ATTRS markerui-system:packages/attrs/src/isAttrsComponent.tsx
  18. data-attrs added in every non-production buildui-system:packages/attrs/src/attrs.tsx
  19. DEBUG is accepted by the config typeui-system:packages/attrs/src/types/config.ts
  20. DEBUG has no runtime effect in attrs (data-attrs is added in every non-production build)ui-system:packages/attrs/src/types/config.ts
  21. Inner component memoized; content-equal re-renders short-circuitui-system:packages/attrs/src/attrs.tsx
  22. Props stabilized by deep equality (useStableValue)ui-system:packages/core/src/useStableValue.ts
  23. Deep equality compares non-plain values (including functions) by referenceui-system:packages/core/src/isEqual.ts
  24. 0 leaf renders on 50 stable-prop re-updates (author's benchmark)ui-system:packages/attrs/benchmarks/results.md
  25. Fast path when no .attrs() / priority attrs configuredui-system:packages/attrs/src/hoc/attrsHoc.tsx
  26. Statics of the wrapped component are hoistedui-system:packages/attrs/src/attrs.tsx
  27. name / component validated in development onlyui-system:packages/attrs/src/init.ts
  28. Exports: attrs (default + named), isAttrsComponent, and typesnpm:@vitus-labs/attrs/lib/index.d.ts
  29. Peer dependencies react >= 19 and @vitus-labs/corenpm:@vitus-labs/attrs/package.json
  30. README: priority attrs are the lowest layer; attrs and explicit props override themnpm:@vitus-labs/attrs/README.md
  31. Rocketstyle exposes the same attrs / compose / statics chainnpm:@vitus-labs/rocketstyle/README.md