attrs API

How to use the attrs function to spread a bag of attributes, events, and properties on a single element.


Description

The attrs function returns an opaque bag that, when interpolated directly inside an opening tag, applies every key of the provided object to the element. Each entry is routed to the correct sink based on its name prefix:

  • name→ set as a regular attribute (or removed when the value is false, null or undefined);
  • @name→ bound as an event listener (@click, @input, ...);
  • .name→ assigned as a JS property on the element (skipping HTML attribute reflection).

When the target is a custom element, camelCase attribute names are automatically converted to kebab-case, matching the behavior of plain interpolated attributes.

On re-renders, keys that disappeared from the new bag are removed from the element, so you can use attrs for conditional or computed attribute sets.


Usage

import { attrs, defineWompo, html, useState } from 'wompo';

export default function Field({ name, type = 'text' }) {
  const [value, setValue] = useState('');
  const inputAttrs = attrs({
    type,
    name,
    value,
    disabled: type === 'hidden',
    '@input': (e) => setValue(e.target.value),
    '.checked': type === 'checkbox' && value === 'on',
  });
  return html`<input ${inputAttrs} />`;
}

defineWompo(Field);

Interpolation rules: the attrs result must be placed directly inside an opening tag, not next to a single attribute. Use it once per element; spreading two bags on the same element is supported, but the order in which the keys are applied follows the order of the bags.


When to use it

Reach for attrs when:

  • you want to forward an unknown set of props from the parent down to an internal element (a typical wrapper component);
  • the set of attributes is conditional or computed and you would otherwise have to branch the template;
  • you need to set a DOM property (.value, .checked, ...) together with attributes and events on the same element.