|
| 1 | +import React, { FormEvent } from 'react' |
| 2 | +import { observer } from 'mobx-react' |
| 3 | +import { FieldState, FormState } from 'formstate-x' |
| 4 | +import { Button, TextField, Container } from '@mui/material' |
| 5 | + |
| 6 | +import { bindTextField } from '../../../mui-binding' |
| 7 | +import FullNameInput, { createState as createFullNameState } from './FullNameInput' |
| 8 | + |
| 9 | +const form = new FormState({ |
| 10 | + name: createFullNameState(), |
| 11 | + email: new FieldState('').validators(validateEmail) |
| 12 | +}) |
| 13 | + |
| 14 | +export default observer(function Demo() { |
| 15 | + |
| 16 | + async function handleSubmit(e: FormEvent<HTMLFormElement>) { |
| 17 | + e.preventDefault() |
| 18 | + // trigger validation when user want to submit |
| 19 | + const result = await form.validate() |
| 20 | + // if error, do nothing (or maybe show a toast?) |
| 21 | + if (result.hasError) return |
| 22 | + // if no error, wo do next things, such as sending HTTP request |
| 23 | + console.log('Submit with:', result.value) |
| 24 | + } |
| 25 | + |
| 26 | + return ( |
| 27 | + <Container component="form" noValidate onSubmit={handleSubmit} maxWidth="xs"> |
| 28 | + <FullNameInput state={form.$.name} /> |
| 29 | + <TextField |
| 30 | + label="Email Address" |
| 31 | + margin="normal" |
| 32 | + fullWidth |
| 33 | + {...bindTextField(form.$.email)} |
| 34 | + /> |
| 35 | + <Button type="submit" fullWidth variant="contained" sx={{ mt: 3 }}> |
| 36 | + Submit |
| 37 | + </Button> |
| 38 | + </Container> |
| 39 | + ) |
| 40 | +}) |
| 41 | + |
| 42 | +function validateEmail(v: string) { |
| 43 | + if (!v) return 'Please input your email!' |
| 44 | +} |
0 commit comments