hono-preact
Overview
Quick Start
The Route Table
Layouts & Nesting
Adding Pages
Active Links
Server Loaders
Loading States
Reloading Data
Prefetching
Streaming
Live Loaders
Realtime Channels
Server Actions
Validation
Optimistic UI
View Transitions
Middleware
CSRF Protection
CLI
Vite Config
Project Structure
Composing Hono Middleware
WebSockets
Rooms & Presence
renderPage
Link Prefetch
Build & Deploy
Overview
Dialog
Popover
Tooltip
Menu
Context Menu
Select
Combobox
Toast
renderElement
useControllableState
mergeRefs
useListNavigation
useTypeahead
useListboxSelection
usePosition
usePositioner
useDismiss
useFocusReturn
useSafeArea
usePresence

mergeRefs#

mergeRefs combines several refs into one callback ref. It is the small piece that lets a component keep its own internal ref to a node while still handing that node to a ref the caller passed in. Function refs are invoked with the node, object refs have their .current assigned, and null/undefined are skipped.

Demo#

measured width: …

Example#

A field that needs its own ref to the input (to measure or focus it) while also forwarding a ref to the caller:

import { mergeRefs } from 'hono-preact-ui';
import { useRef } from 'preact/hooks';
import type { Ref } from 'preact';

export function Field({ inputRef }: { inputRef?: Ref<HTMLInputElement> }) {
  const internalRef = useRef<HTMLInputElement>(null);

  const focus = () => internalRef.current?.focus();

  // Both refs receive the same node.
  return (
    <div>
      <input ref={mergeRefs(internalRef, inputRef)} />
      <button type="button" onClick={focus}>
        Focus
      </button>
    </div>
  );
}

This is the same helper renderElement uses internally to merge a consumer's ref with the framework's own, so passing a ref through the render prop always keeps both wired up.

Signature#

import { mergeRefs } from 'hono-preact-ui';

function mergeRefs<T>(
  ...refs: (Ref<T> | null | undefined)[]
): (node: T | null) => void;

It returns a single callback ref. Pass that to an element's ref, and every ref you merged receives the node.

Parameters#

ParameterTypeDescription
...refs(Ref<T> | null | undefined)[]The refs to combine. Function refs are called, object refs are assigned, nullish refs are skipped.

Returns a callback ref, (node: T \| null) => void, that forwards the node to every ref passed in.