Hooks

useFormField

Access the context provided by a parent FormField component. Useful for building custom form inputs that integrate with FormField's label, error, size, and accessibility features.

Basic Usage

The useFormField hook reads context values from a parent FormField. Below, see how the context is provided to child components.

Please enter a valid email

FormField Context Values

name:
email
size:
md
error:
Please enter a valid email
ariaId:
auto-generated
<script lang="ts">
  import { FormField, Input, Card } from 'sv5ui';
  import { useFormField } from 'sv5ui';

  // Inside a custom component wrapped by FormField:
  const ctx = useFormField();
</script>

<!-- Parent usage -->
<FormField label="Email" name="email" error="Invalid email" size="sm">
  <Input placeholder="you@example.com" />
</FormField>

<!-- Reading context values -->
{#if ctx}
  <Card variant="soft">
    <p><strong>Name:</strong> {ctx.name}</p>
    <p><strong>Size:</strong> {ctx.size}</p>
    <p><strong>Error:</strong> {ctx.error}</p>
    <p><strong>Aria ID:</strong> {ctx.ariaId}</p>
  </Card>
{/if}

Custom Component

Use useFormField inside custom components to inherit FormField context automatically.

Bio is required

<!-- CustomInput.svelte -->
<script lang="ts">
  import { useFormField } from 'sv5ui';

  const ctx = useFormField();
  // ctx?.name, ctx?.size, ctx?.error, ctx?.ariaId
  // Use these to sync with the parent FormField
</script>

<input
  id={ctx?.ariaId}
  name={ctx?.name}
  aria-invalid={!!ctx?.error}
  class="..."
/>

<!-- Usage -->
<FormField label="Username" name="username" error="Required">
  <CustomInput />
</FormField>

Return Values

NameTypeDefault
namestring-
sizestring-
errorstring | boolean-
ariaIdstring-