@muzikanto/observable-form
v2.7.2
Published
Form state manager
Downloads
12
Maintainers
Readme
Observable-form
Introduction
- based on observable
- create form state and helpers
- create form fields
- easy migration from formik (not all props)
- support confirm submit
- formik How to avoid rerendering? #342
- formik Every input field in form rerenders when just one changed #367
- optimize renders every changes
Installation
npm i @muzikanto/observable @muzikanto/observable-form
# or
yarn add @muzikanto/observable @muzikanto/observable-form
Examples
example code example with hooks code
create api
interface State {
text: string;
field: string;
deep: {
one: string;
two: string;
};
arr: string[];
}
const validationSchema = Yup.object().shape({
text: Yup.string()
.required()
.max(5),
field: Yup.string()
.required()
.max(3),
});
const form = createForm<FormState>({
validateOnMount: false,
initialState: {
text: '123',
field: '',
deep: { one: '1', two: '' },
arr: ['1', '2', '3'],
},
validationSchema,
});
form.values.watch(state => console.log('values: ', state));
create field
function FieldInput(props: { name: string }) {
const { value, error, touched, setFieldTouched, setFieldValue } = useField<string>({
name: props.name,
validate: v => {
if (false) {
return 'my custom error';
}
},
});
const touchedAndError = Boolean(touched && error);
return (
<>
<input
value={value}
onChange={e => setFieldValue(e.target.value)}
onBlur={() => setFieldTouched(true)}
/>
{touchedAndError && <span>{error}</span>}
</>
);
}
Use
function FormComponent() {
return (
<Form
form={form}
formId='form-id'
formProps={{}}
Confirm={({ open, onClose, onAccept }) => (
<Dialog open={open} onClose={onClose}>
<DialogContent>
<Button
onClick={() => {
onClose();
form.reset();
}}
>
Reject
</Button>
<Button onClick={onAccept}>Accept</Button>
</DialogContent>
</Dialog>
)}
>
<FieldInput name='text' />
<FieldInput name='field' />
<FieldInput name='deep.one' />
<button onClick={() => form.reset()}>RESET</button>
<button onClick={() => form.validate()}>VALIDATE</button>
<Submit
component={({ onClick, disabled }) => (
<button onClick={onClick} disabled={disabled}>
Submit
</button>
)}
/>
<ErrorMessage name='field' component={props => <span {...props} />} />
</Form>
);
}