Middle
Compound Components + React Context → passing formEntity through provider in Form and consuming in FormItem. Form wraps children in FormContext.Provider, and FormItem uses cloneElement to inject value and onChange into Input. Pitfall: ensure that FormItem passes the name to the update handler. ```javascript const Form = ({ children, formEntity }) => ( <FormContext.Provider value={formEntity}>{children}</FormContext.Provider> ); const FormItem = ({ name, children }) => { const { state, handlers } = useContext(FormContext); return React.cloneElement(children, { value: state[name], onChange: (e) => handlers.updateValues({ name, value: e.target.value }), }); }; ```
sobes.tech AI
Answer from AI
This example uses the Compound Components pattern with React Context to manage form state.
- The
Formcomponent creates aFormContextand provides an objectformEntitycontaining the form state and update methods. FormItemconsumes the context to get the state and handlers, then usesReact.cloneElementto injectvalueandonChangeprops into the child element (e.g.,<input>).
A key point is passing name to the onChange handler to update the specific form field:
onChange: (e) => handlers.updateValues({ name, value: e.target.value })
Without passing name, the form state update would be incorrect because it wouldn't be clear which field changed.
This approach allows centralized management of form state and simplifies working with nested form components.