-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
72 lines (58 loc) · 1.81 KB
/
index.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React, { useState } from 'react';
import { rff, FormScope, FormField } from 'react-formstate-fp';
import { library as validation } from 'react-formstate-validation';
function Input({label, value, help, onChange, onBlur}) {
return (
<div>
<div>{label}</div>
<input type='text' value={value} onChange={onChange} onBlur={onBlur}/>
<div>{help}</div>
</div>
);
}
function RffInput({formstate, modelKey, form, ...other}) {
return (
<Input
value={rff.getValue(formstate, modelKey)}
help={form.calculatePrimed(formstate, modelKey) && rff.getMessage(formstate, modelKey)}
onChange={e => rff.handleChange(form, e.target.value, rff.getId(formstate, modelKey))}
onBlur={() => rff.handleBlur(form, rff.getId(formstate, modelKey))}
{...other}
/>
);
}
export default function TestForm({model, grabFormstate, grabForm}) {
const [formstate, setFormstate] = useState(() => rff.initializeFormstate(model));
const form = {
setFormstate,
adaptors: [RffInput],
calculatePrimed: rff.primeOnChange
};
grabFormstate(formstate);
grabForm(form);
return (
<form onSubmit={e => handleSubmit(e, form)}>
<FormScope formstate={formstate} form={form}>
<FormField name='test' required validate={validateTest}>
<RffInput label='Test'/>
</FormField>
</FormScope>
<input type='submit' value='Submit' disabled={rff.isPrimedModelInvalid(formstate, form.calculatePrimed)}/>
</form>
);
}
function validateTest(value) {
if (value.length < 8) {
return 'Test must be at least 8 characters.';
}
}
function handleSubmit(e, form) {
e.preventDefault();
form.setFormstate(fs => {
fs = rff.validateForm(fs, form);
if (rff.isModelValid(fs)) {
alert(JSON.stringify(fs.model));
}
return fs;
});
}