attrs

Reactive access to every attribute on the host, declared as a prop or not.

attrs: Record<string, string | null>
const view = useState({
  get compact() {
    return attrs.density === "compact";
  },
});

attrs.tabindex ??= 0;
attrs["aria-expanded"] = open;

Reading

Read Result
attrs.name The attribute's text, or null when it is absent
In an observer or getter Subscribes. It re-runs when that attribute changes, is added or is removed

Writing

Value written Result
null, undefined, false removeAttribute(name)
true setAttribute(name, "")
anything else setAttribute(name, String(value))

The attribute mirror is created on first use and watches the host with a MutationObserver until the element is removed. For typed, validated attributes, use defineProps.

Example

Previewindex.htmldensity-label.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>attrs demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/dist/theme.css">
  <script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
  <import-element from="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/components/button.html"></import-element>

  <import-element from="./density-label.html"></import-element>

  <density-label></density-label>
</body>
</html>
<custom-element name="density-label">
  <script>
    const view = useState({
      get text() {
        return attrs.density === "compact" ? "Compact" : "Comfortable";
      },
    });

    function toggle() {
      attrs.density = attrs.density === "compact" ? null : "compact";
    }
  </script>

  <ui-button variant="outline" onclick="toggle()"><slot name="#view.text"></slot></ui-button>
</custom-element>

Edit this page on GitHub · View as Markdown