refs

Elements with a ref="name" attribute in the component's markup, keyed by name.

refs: Record<string, Element>
<canvas ref="chart"></canvas>
onConnected(() => {
  const context = refs.chart.getContext("2d");
});

Behaviour

Topic Detail
Timing Empty while the script's top level runs. Filled as the markup is processed, before onConnected hooks
Reactive refs is a reactive object, so an observe that reads refs.chart runs again once the element exists
Loops and conditions Elements inside repeat or <is-visible> are added when they are mounted. The last mounted element with a name wins, and removed content is not taken out
ref="control" Also makes the element the delegated form control in form-associated components. See ref

Example

Previewindex.htmldraw-dot.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>refs 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="./draw-dot.html"></import-element>

  <draw-dot></draw-dot>
</body>
</html>
<custom-element name="draw-dot">
  <script>
    function draw(event) {
      const canvas = refs.canvas;
      const box = canvas.getBoundingClientRect();
      const context = canvas.getContext("2d");
      context.fillStyle = getComputedStyle(host).color;
      context.beginPath();
      context.arc(event.clientX - box.left, event.clientY - box.top, 4, 0, Math.PI * 2);
      context.fill();
    }
  </script>

  <style>
    canvas {
      border: 1px solid var(--border);
      border-radius: var(--radius-md);
      cursor: crosshair;
    }
  </style>

  <canvas ref="canvas" width="240" height="120" onclick="draw(event)"></canvas>
</custom-element>

Edit this page on GitHub · View as Markdown