useRef in <Form /> Component | Informed | PWA Studio | React

392 Views Asked by At

I need to execute the form submit using useRef(). I'm trying to reference the component provided by 'informed' (PWA Studio forms lib), but the reference doesn't work.The reference isn't work to informed Form but I don't know why. I tried the same reference using normal html form <form ref={formRef}>... and in this case worked.

const formRef = useRef(null);
...
// 'informed Form'
<Form ref={formRef}>...</Form>

// It does't submit the form after function executed
const handleSubmit = () => {
  formRef.current && formRef.current.submit();
};
1

There are 1 best solutions below

0
On

In informed it is really not possible to refer to it through the useRef simple way. To achieve your goal you can use the getApi={formRef.current} prop in the Form component

// You can create your useRef() in this way
const formApiRef = useRef(null);
const setFormApi = useCallback(api => (formApiRef.current = api), []);

// In your form component set the apiForm
<Form getApi={setFormApi}> ... </Form>

// In your handleSubmit function in order to submit you can do this
const handleSubmit = useCallback(() => {
    const { current: formApi } = formApiRef;

    if (formApi) {
      formApi.submitForm();
    }
  }, [applyCoupon, cartId]);