BoldDeskWe are launching BoldDesk on Product Hunt soon. Learn more & follow us.
Hi sycnfusion Team,
I'm using Textbox component and handling error by using react-hook-form.
Link sample: https://stackblitz.com/edit/react-ycxjgx?file=index.js
Field name is required. When I submit data with empty name, I want to show the error message and focus on the 'name' field. But it has error and show this message.
How can I fix this issue?
Thanks
Hi Ton,
The {…field} spread operator was removed and field.value and field.onchange props were passed explicitly to the TextBoxComponent in order to ensure proper integration with react-hook-form, allowing for correct form validation and submission handling. Please find the code snippet and sample for your reference.
<Controller name="name" control={control} rules={{ required: true }} render={({ field }) => { return ( <TextBoxComponent placeholder="name" value={field.value} onChange={field.onChange} /> ); }} /> |
Sample: https://stackblitz.com/edit/react-ycxjgx-nijyvb?file=index.js
Regards,
Priyanka K
Hi Priyanka,
Thanks for your support.
When I submit data with an empty name, I want to show the error message and focus on the Textbox.
How can I handle this case?
Thanks
Ton, we have modified the earlier updated sample to achieve your requirement,
find the sample code below:
import { useEffect, useRef } from 'react';
function Default() { const { handleSubmit, control, formState: { errors }, setError, } = useForm({ defaultValues: { name: '', }, });
function handleSave(data) { console.log('data'); }
const nameRef = useRef();
useEffect(() => { if (errors.name) { nameRef.current.element.focus(); } }, [errors]);
return ( <div className="control-pane"> <form onSubmit={handleSubmit(handleSave.bind(this))}> <div> <Controller name="name" control={control} rules={{ required: true }} render={({ field }) => { return ( <TextBoxComponent id="nameInput" placeholder="name" onChange={field.onChange} ref={(scope) => { nameRef.current = scope; }} /> ); }} /> {errors.name && <label>Name is required</label>} <button>Submit</button>
|
Find the modified sample here: https://stackblitz.com/edit/react-ycxjgx-bjndta?file=index.js
Hi Ton,
Thanks for your update. Please let us know if you require any further assistance. We are happy to assist you.
Regards,
Priyanka K