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.
npx shadcn@latest add https://ui.bld8.dev/r/example-form-review-request.jsonComplete source
/*!
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>;
}