/
FormWrapper.js
84 lines (75 loc) · 1.95 KB
/
FormWrapper.js
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
73
74
75
76
77
78
79
80
81
82
83
84
import React from 'react';
import update from 'immutability-helper';
import ReactTextField from '../src/components/ReactTextField';
class FormWrapper extends React.Component {
constructor(props) {
super(props);
const fields = props.children.map((child) => {
const name = child.props.name;
const value = { name, isValid: false, value: null };
return value;
});
const initialState = {
fields,
};
this.state = initialState;
this.canSubmit = this.canSubmit.bind(this);
this.onClick = this.onClick.bind(this);
this.onChange = this.onChange.bind(this);
this.afterValidate = this.afterValidate.bind(this);
}
afterValidate(isValid, name) {
const index = this.state.fields.findIndex((field) => {
return field.name === name;
});
if (index === -1) {
return;
}
this.setState({
fields: update(this.state.fields, { [index]: { isValid: { $set: isValid } } }),
});
}
onChange(e, name) {
const index = this.state.fields.findIndex((field) => {
return field.name === name;
});
if (index === -1) {
return;
}
this.setState({
fields: update(this.state.fields, { [index]: { value: { $set: e.target.value } } }),
});
}
onClick(e) {
e.preventDefault();
console.log(this.state.fields);
}
canSubmit() {
return this.state.fields.every(f => f.isValid === true);
}
render() {
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
onChange: this.onChange,
afterValidate: this.afterValidate,
}),
);
return (
<div>
<form>
{childrenWithProps}
<button
disabled={!this.canSubmit()}
onClick={this.onClick}
>
Submit
</button>
</form>
</div>
);
}
}
FormWrapper.propTypes = {
children: React.PropTypes.node,
};
export default FormWrapper;