I have a form, and this form was getting too complex for one component.
So I made a subsection for a part of the form which has multiple dynamic inputs and gives a single output and validates itself. It doesn't have a submit button, on every change it just passes back the computed result and if it is validated successfully or not.
// Contains multiple input fields, passes its result when
// filled in properly and errors if not filled in properly
// so I can disable the submit button.
// Also contains a clear method internally.
<AddItemPresetsInput
onChange={handlePresetItemsChange}
errorsChanged={handlePresetErrorsChange}
></AddItemPresetsInput>
I want the parent, after being submitted, to clear this subform and reset it. What I'd love to do is call the child's clear()
method. But this appears to be bad practice from this post:
So I see a few options:
- Use Refs to call child's clear method - Not recommended in React's docs: Avoid using refs for anything that can be done declaratively.
- Lift the state of the subform to the parent which would allow me to change props to clear the form. But this goes against my initial goal of abstracting this logic to a subcomponent as the child can do everything self contained and it makes the parent complex.
Use the key attribute and change the key on submit - this is what I'm doing, it just seems to be hacky.
<AddItemPresetsInput onChange={handlePresetItemsChange} errorsChanged={handlePresetErrorsChange} key={presetItemsKey} ></AddItemPresetsInput>
Am I missing an option? It seems option 2 is the way to go with how the React Docs recommend doing it.