React can pass onChange functions from functional parent to functional child for the child to use to update the parent. But writing the same onChange functions in several Form building components seems redundant - and I'm hoping there's a better way to build forms faster or a more global method of a child calling parent functions WITHOUT the use of classes.
I've attempting to create an external function and importing it on all components that build forms and pass on onChange to a Field component. But after importing them, they do not have automatically have access to the setValue part of the statehook
I tried Context, but you can't send a dynamic, initial state that has all of the field / values for your form so you get an error regarding controlled and uncontrolled inputs
function Episode({ match }) {
const [formData, setData] = useState(content.form);
...retrieve data from API …
const updateFieldState = e => {
switch(e.target.type){
case 'text':
case 'textarea':
case 'select-one':
setValues({
...formValues,
[e.target.id]: e.target.value
});
break;
case "checkbox":
. . . . . .(you get the idea here)
}
return {
<Form>
<Field id="item_title" changeHandler={updateFieldState}/>
<Field id="item_subtitle" changeHandler={updateFieldState}/>
. . . . . .(custom child component Field that creates an input and adds updateFieldState to its onClick event )
<Form>
}
}
As it stands, I would not only need to redundantly add this changeHandler to every field on this form, but I'd have to redundantly rewrite updateFieldState on EVERY component that builds a from like this creating.
Any help, suggestions or tutorials on how to build faster forms without the use of classes would be appreciated.