Skip to main content

createId

Generate unique, SSR-safe identifiers for accessibility relationships and form controls.

View as Markdown

createId returns an accessor for a string identifier used in accessibility bindings (aria-labelledby, aria-describedby, aria-controls, for). It returns the ID you supply when there is one, and otherwise a prefixed ID from Solid’s createUniqueId().

Import#

import { createId } from 'moraine/utils'

Signature#

function createId(
  deterministicId?: () => string | null | undefined,
  prefix = 'mo',
): Accessor<string>

Usage Example#

src/CustomField.tsx
import { createId } from 'moraine/utils'

interface CustomFieldProps {
  id?: string
  label: string
}

export function CustomField(props: CustomFieldProps) {
  // Uses props.id when set; otherwise generates a unique "input-..." ID.
  const inputId = createId(() => props.id, 'input')
  const descriptionId = () => `${inputId()}-desc`

  return (
    <div>
      <label for={inputId()}>{props.label}</label>
      <input
        id={inputId()}
        aria-describedby={descriptionId()}
        class="border px-3 py-1.5 rounded-md"
      />
      <p id={descriptionId()} class="text-xs text-muted-foreground">
        Required field
      </p>
    </div>
  )
}

Priority Rules#

  1. If deterministicId returns a non-empty string, the accessor returns that string.
  2. Otherwise (the function is omitted, or returns null, undefined, or an empty string), the accessor returns the generated ID: prefix (default 'mo'), a hyphen, and Solid’s createUniqueId().

The generated ID is created once per call, so it stays stable when deterministicId changes between a string and undefined. Because it comes from createUniqueId(), server and client render the same ID during hydration.