Form - onChange Example?

1 Answer 1083 Views
Form
Brent
Top achievements
Rank 1
Iron
Brent asked on 29 May 2021, 02:06 PM | edited on 29 May 2021, 02:08 PM

I am developing a data entry form that involves complex relationships between individual fields and the data service.  I may be in a situation where Form.onChange may be helpful, but I'm not sure.  The online documentation says "Use onChange only if you cannot achieve the desired behavior through the Field component by FormRenderProps." but doesn't actually given an example.  How do I call this method?

Note: This is not about FieldRenderProps.onChange.

Do I have to stick the component in a variable and call the method directly?  Is it like this?

function FuncyComponent() { const someData = {id: 123, etc}; const form = <Form initialValues={someData} render={formRenderProps =>
<FormElement>some fields</FormElement>} />
; const handleButtonClick = (event: whatever) => { form.onChange("id", {value: 9876}); }; return <div> {form} <button onClick={handleButtonClick}>Change The ID</button> </div>; }


1 Answer, 1 is accepted

Sort by
0
Accepted
Stefan
Telerik team
answered on 31 May 2021, 11:37 AM

Hello, Brent,

Yes, this is the approach.

We need to take the ref of the component and then use it like this:

const MyForm = React.useRef()
                    <Form
                        ref={MyForm}

MyForm.current.onChange('someField', {value: someValue});

Regards,
Stefan
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Brent
Top achievements
Rank 1
Iron
commented on 01 Jun 2021, 12:59 AM

I'll try that. Thanks.
Brent
Top achievements
Rank 1
Iron
commented on 01 Jun 2021, 03:26 PM

For the benefit of those reading this post later on, I'll say that for TypeScript to be happy with how I create the ref, I had to use this syntax:

const formRef = React.useRef<Form>(null);

I had to use "(null)" and not just "()" because "()" returns a MutableObjectRef<T>. "(null)" returns a Ref<T>. Form's ref property is of type LegacyRef<Form>. React defines those ref types like this:

type LegacyRef<T> = string | Ref<T>;
type Ref<T> = RefCallback<T> | RefObject<T> | null;
type LegacyRef<T> = string | Ref<T>;

And it defines a few useRef overloads like this:

function useRef<T = undefined>(): MutableRefObject<T | undefined>; // Note: no parameter!
function useRef<T>(initialValue: T|null): RefObject<T>; // Note: takes a parameter!

So you have to do "(null)" to get an object TypeScript believes is compatible with Form's ref property.
Tags
Form
Asked by
Brent
Top achievements
Rank 1
Iron
Answers by
Stefan
Telerik team
Share this question
or