Forms

React Hook Form.

Optional bindings for the form state already in your application.

LIVE PREVIEWTry it. It works.

Install the source

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/react-hook-form.json

Registry setup · Examples · API and behavior · Open the playground

COMPLETE EXAMPLES

Use it in context.

Each example includes its imports, data and state. The preview runs that same source. Include the stylesheet once in your application.

Use existing React Hook Form state

The optional adapter links field labels, errors, native refs and a working local submit handler.

Loads this example when you need it.

Keyboard

  • Tab reaches the registered field.
  • Invalid submit uses React Hook Form focus and error behaviour.

States covered

  • Empty required input
  • Validation error
  • Submitted value

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-basic-react-hook-form.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import {useState} from 'react';
import {useForm} from 'react-hook-form';
import {Button,Input,OTPInput,Select,UIProvider} from '@bld8/ui';
import {RHFControl,RHFField} from '@bld8/ui/react-hook-form';
import '@bld8/ui/styles.css';
export default function HookFormExample(){
  const form=useForm<{name:string;reviewer:string|null;code:string}>({defaultValues:{name:'',reviewer:null,code:''}}),[saved,setSaved]=useState('');
  return <UIProvider><form onSubmit={form.handleSubmit(values=>setSaved(values.name+' / '+values.reviewer))}>
    <RHFField control={form.control} name="name" label="Example workspace name" required rules={{required:'Enter an example name.'}}>{field=><Input {...field}/>}</RHFField>
    <RHFControl control={form.control} name="reviewer" rules={{required:'Choose an example reviewer.'}}>{binding=><Select {...binding} label="Example form reviewer" required options={[{value:'maya',label:'Maya Chen',description:'Interface review'},{value:'sam',label:'Sam Rivera',description:'Keyboard review'}]}/>}</RHFControl>
    <RHFControl control={form.control} name="code" rules={{validate:value=>value.length===6||'Enter six example digits.'}}>{binding=><OTPInput {...binding} label="Example form code" length={6} hint="Format validation only; no authentication service."/>}</RHFControl>
    <Button type="submit">Submit hook form example</Button><p role="status">{saved?'Local result: '+saved:''}</p>
  </form></UIProvider>;
}

Conditional reviewers and repeatable form rows

Compose grouped channels, a conditional reviewer list and linked validation errors with React Hook Form. A rejected local save preserves every draft value for correction.

Keyboard

  • Submit an incomplete request to focus the first invalid field. Error-summary links return to the named field.
  • Enable Include reviewers to reveal email fields. Add reviewer focuses the new row; remove keeps a valid nearby focus target.
  • Reset restores host-owned defaults. Pending submission disables editing; failed saves keep values and show a linked error.

States covered

  • Fieldset and CheckboxGroup
  • React Hook Form integration
  • Conditional fields
  • Repeatable rows
  • Linked error summary
  • Server error retention
  • Host reset
  • Abortable local save

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-form-review-request.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useEffect,useRef,useState} from 'react';
import {Controller,useFieldArray,useForm,type FieldPath} from 'react-hook-form';
import {Button,Checkbox,CheckboxGroup,Fieldset,FormErrorSummary,Input,Reveal} from '@bld8/ui';
import {RHFControl,RHFField} from '@bld8/ui/react-hook-form';
interface Values {title:string;channels:string[];includeReviewers:boolean;reviewers:{email:string}[]}
const defaults:Values={title:'',channels:['email'],includeReviewers:false,reviewers:[{email:''}]};
const channelOptions=[{value:'email',label:'Email'},{value:'in-app',label:'In-app'}];
function wait(signal:AbortSignal){return new Promise<void>((resolve,reject)=>{const done=()=>{signal.removeEventListener('abort',abort);resolve();},timer=setTimeout(done,160),abort=()=>{clearTimeout(timer);reject(new DOMException('Cancelled','AbortError'));};if(signal.aborted)abort();else signal.addEventListener('abort',abort,{once:true});});}
export default function ReviewRequestFormExample(){
  const form=useForm<Values>({defaultValues:defaults,mode:'onBlur'}),rows=useFieldArray({control:form.control,name:'reviewers'});
  const includeReviewers=form.watch('includeReviewers'),pending=form.formState.isSubmitting,request=useRef<AbortController|null>(null);
  const [rejectNext,setRejectNext]=useState(false),[status,setStatus]=useState('Local form example. No review is sent.');
  useEffect(()=>()=>request.current?.abort(),[]);
  useEffect(()=>{if(!pending&&form.formState.errors.title?.type==='server')form.setFocus('title');},[pending,form.formState.errors.title,form.setFocus]);
  useEffect(()=>{if(!includeReviewers)form.clearErrors('reviewers');},[includeReviewers,form.clearErrors]);
  const errors:Record<string,string|undefined>={title:form.formState.errors.title?.message,channels:form.formState.errors.channels?.message};
  if(includeReviewers)rows.fields.forEach((row,index)=>{errors['reviewers.'+index+'.email']=form.formState.errors.reviewers?.[index]?.email?.message;});
  async function save(values:Values){
    const controller=new AbortController();request.current?.abort();request.current=controller;setStatus('');form.clearErrors('root.service');
    try{await wait(controller.signal);if(controller.signal.aborted)return;
      if(rejectNext){setRejectNext(false);form.setError('title',{type:'server',message:'This local request title is already used.'},{shouldFocus:true});form.setError('root.service',{message:'The local save was rejected. Your entries are kept.'});return;}
      setStatus('Request prepared locally with '+(values.includeReviewers?values.reviewers.length:0)+' reviewers. No message was sent.');
    }catch(error){if(!controller.signal.aborted)form.setError('root.service',{message:error instanceof Error?error.message:'Unable to prepare request.'});}
    finally{if(request.current===controller)request.current=null;}
  }
  function reset(){request.current?.abort();form.reset(defaults);setStatus('Form defaults restored.');}
  return <div style={{display:'grid',gap:20,maxWidth:680}}><Checkbox label="Reject next local save" checked={rejectNext} onCheckedChange={setRejectNext} disabled={pending}/>
    <form noValidate aria-label="Review request form" aria-busy={pending||undefined} onSubmit={form.handleSubmit(save)} onReset={event=>{event.preventDefault();reset();}} style={{display:'grid',gap:24}}>
      <FormErrorSummary error={form.formState.errors.root?.service?.message} errors={errors} fieldLabels={{title:'Request title',channels:'Delivery channels'}} onFocusField={name=>form.setFocus(name as FieldPath<Values>)}/>
      <Fieldset legend="Request details" hint="Start with a short title and a delivery choice." disabled={pending}>
        <RHFField control={form.control} name="title" label="Request title" required rules={{required:'Enter a request title.',minLength:{value:3,message:'Use at least three characters.'}}}>{field=><Input {...field} autoComplete="off"/>}</RHFField>
        <RHFControl control={form.control} name="channels" rules={{validate:value=>value.length>0||'Choose at least one delivery channel.'}}>{binding=><CheckboxGroup {...binding} label="Delivery channels" options={channelOptions} required/>}</RHFControl>
      </Fieldset>
      <Controller control={form.control} name="includeReviewers" render={({field})=><Checkbox label="Include reviewers" name={field.name} inputRef={field.ref} checked={field.value} onCheckedChange={field.onChange} onBlur={field.onBlur} disabled={pending}/>}/>
      <Reveal open={includeReviewers}><Fieldset legend="Reviewers" hint="Up to three local reviewer rows. Hiding this group preserves its draft." disabled={pending}>
        {rows.fields.map((row,index)=><div key={row.id} style={{display:'grid',gridTemplateColumns:'minmax(0,1fr) auto',gap:12,alignItems:'end'}}>
          <RHFField control={form.control} name={('reviewers.'+index+'.email') as `reviewers.${number}.email`} label={'Reviewer '+(index+1)+' email'} required rules={{validate:value=>!includeReviewers||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)||'Enter a valid reviewer email.'}}>{field=><Input {...field} type="email" autoComplete="off"/>}</RHFField>
          <Button variant="ghost" size="sm" aria-label={'Remove reviewer '+(index+1)} disabled={rows.fields.length<=1} onClick={()=>{rows.remove(index);requestAnimationFrame(()=>form.setFocus(('reviewers.'+Math.max(0,index-1)+'.email') as FieldPath<Values>));}}>Remove</Button>
        </div>)}
        <Button variant="secondary" disabled={rows.fields.length>=3} onClick={()=>rows.append({email:''})}>Add reviewer</Button>
      </Fieldset></Reveal>
      <div style={{display:'flex',gap:12,flexWrap:'wrap'}}><Button type="submit" loading={pending}>Prepare review request</Button><Button variant="secondary" type="reset" disabled={pending}>Reset review form</Button></div>
    </form><p role="status">{status}</p>
  </div>;
}

Quick reference

React / TypeScript
import { RHFField, RHFControl } from "@bld8/ui/react-hook-form";

<RHFField control={form.control} name="name" label="Name">
  {field => <Input {...field} />}
</RHFField>
<RHFControl control={form.control} name="tags">
  {binding => <MultiSelect {...binding} label="Tags" options={options} />}
</RHFControl>

In the workspace or ZIP starter, import components from @bld8/ui and include @bld8/ui/styles.css once. Registry installations use your local bld8/ source path. Wrap overlays in UIProvider.

API & behaviour

Optional peer integration: install react-hook-form when using this subpath. RHFField links native input labels and field errors. RHFControl binds value, onValueChange, onBlur, inputRef, disabled and error to label-owning controls such as Select, MultiSelect and DatePicker. Rules, control, defaultValue and shouldUnregister follow useController. Define explicit empty defaults; normal RHF Controller/register remain supported. The integration guide includes a runnable HTTP-backed example.

RHFField

RHFField public properties
PropTypeDefault
childrenRequired(field: ControllerRenderProps<T, N>) => ReactNode—
labelRequiredstring—
nameRequiredN—
controlControl<T, any, T> | undefined—
defaultValuePathValueImpl<T, N> | undefined—
disabledboolean | undefined—
exactboolean | undefined—
hintstring | undefined—
requiredboolean | undefined—
rulesOmit<RegisterOptions<T, N>, "disabled" | "valueAsNumber" | "valueAsDate" | "setValueAs"> | undefined—
shouldUnregisterboolean | undefined—

RHFControl

RHFControl public properties
PropTypeDefault
childrenRequired(binding: RHFControlBinding<T, N>) => ReactNode—
nameRequiredN—
controlControl<T, any, T> | undefined—
defaultValuePathValueImpl<T, N> | undefined—
disabledboolean | undefined—
exactboolean | undefined—
rulesOmit<RegisterOptions<T, N>, "disabled" | "valueAsNumber" | "valueAsDate" | "setValueAs"> | undefined—
shouldUnregisterboolean | undefined—

Tables come from the public TypeScript declarations. Related types and function parameters are shown alongside their component. A dash means no default is declared at the public function boundary.

Related controls

Notes to self

Test this component with real content, keyboard input and both themes. The example is a starting point; labels, error handling and behaviour still need to fit the application.