|
1 | | -### Cascade Forms |
2 | 1 |
|
3 | | -clone, samples available via `yarn storybook` |
| 2 | +### Cascade Forms - state-driven container/controls renderer |
| 3 | + |
| 4 | +Simple engine for render component / group depends on common state |
| 5 | + |
| 6 | + |
| 7 | +`yarn install @code4bones/react-cascade-forms` |
| 8 | + |
| 9 | +```tsx |
| 10 | + |
| 11 | +import CascadeForms , { |
| 12 | + FormItems, |
| 13 | + ControlRenderProps, |
| 14 | + FormState, |
| 15 | + FormItem, |
| 16 | + OnChangeFn, |
| 17 | + FormActions } from "@code4bones/react-cascade-forms"; |
| 18 | + |
| 19 | + |
| 20 | +... |
| 21 | + |
| 22 | +const FORM : FormItems = [ ... ] // check samples ! |
| 23 | + |
| 24 | +const actions = createRef<FormActions>(); |
| 25 | + |
| 26 | +const [formState,setFormState] = React.useState<FormState>({ |
| 27 | + name:{ // default state, conforms to FormState |
| 28 | + value:"", |
| 29 | + } |
| 30 | +}); |
| 31 | + |
| 32 | +const onRender = (formState:FormState,item:FormItem,onChange:OnChangeFn) => { |
| 33 | + switch ( item.type ) { |
| 34 | + case "custom": |
| 35 | + // Signature = FormControlRenderFn |
| 36 | + return <CustomCtrl formState={formState} item={item} onChange={onChange} />; |
| 37 | + default: |
| 38 | + return <div>Unexpected type {item.type}</div> |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | +const onUpdate = (state:any) => { |
| 43 | + console.log("Live State",state); |
| 44 | + setFormState(state); |
| 45 | +}; |
| 46 | + |
| 47 | +const onReadState = () => { |
| 48 | + // read active values ( visible ) only |
| 49 | + const state = actions.current?.getState(); |
| 50 | + /* state { |
| 51 | + [id]:{ |
| 52 | + value:..., |
| 53 | + state: // => false if no error, or joined string from ValidationError[] (fastest-validator) |
| 54 | + } |
| 55 | + } |
| 56 | + */ |
| 57 | + console.log("Actual state",state); |
| 58 | +}; |
| 59 | + |
| 60 | +<CascadeForms |
| 61 | + ref={actions} |
| 62 | + form={FORM} |
| 63 | + formState={formState} |
| 64 | + onRender={onRender} |
| 65 | + onUpdate={onUpdate} /> |
| 66 | + |
| 67 | +<Button text="Read state" onClick={onReadState} /> |
| 68 | +... |
| 69 | +``` |
| 70 | + |
| 71 | +Samples available via storybook. |
| 72 | + |
| 73 | +That's all, folks ! |
| 74 | + |
| 75 | + |
4 | 76 |
|
0 commit comments