fabian-hiller / modular-forms

The modular and type-safe form library for SolidJS, Qwik and Preact
https://modularforms.dev
MIT License
1.05k stars 55 forks source link

[Question] Is it possible to have custom input without ref? #178

Open isergey opened 9 months ago

isergey commented 9 months ago

Hi! Thank you so much for such a wonderful library!

I noticed that in all the examples, ref is used to access native browser elements. But what if my input is completely custom? For example:


const CustomBoolean = ({initValue, onChange}) => {
   const [value, setValue] = useState(initValue)

   useEffect(() => {
       onChange(value)
   }, [value])

   return (
       <div>
           <span onClick={() => setValue(true)}>{value ? 'v': '-'}</span>
           <span onClick={() => setValue(false)}>{!value ? 'v': '-'}</span>
       </div>
   )
}

This is just a Boolean input for clarity. But there may be a more complex input, for example, handwritten text recognized by a neural network :)

How can such an input be integrated into the form? Thank you in advance!

fabian-hiller commented 9 months ago

Thanks for creating this issue! In this case just ignore the provided props of the Field component and use setValue instead.

14gasher commented 8 months ago

FWIW, if you do not have an input, calling setValue will not update the formStore values. Wasted a bit of time trying to figure that out haha.

To resolve, I'm currently using hidden inputs.

<>
  <CustomInput 
    field1={getValue(form, 'field1')} 
    field2={getValue(form, 'field2')} 
    onField1={v => setValue(form, 'field1', v)}
    onField2={v => setValue(form, 'field2', v)}  
    />
    <Form.Field name="field1">{createHiddenInput}</Form.Field>
    <Form.Field name="field2">{createHiddenInput}</Form.Field>
</>
fabian-hiller commented 8 months ago

I don't think a hidden field is necessary. Instead, you should wrap your custom field inside our <Field /> component because it manages the lifecycle of the field.

14gasher commented 8 months ago

@fabian-hiller, this custom input sets 2 values in the form. I attempted to double wrap the Field component, and that did not appear to work.

fabian-hiller commented 8 months ago

Okay. That would be exactly the approach I would take, but I am not currently deep enough into Modular Forms to know directly why it might not work in your case.