|
|
@@ -0,0 +1,72 @@
|
|
|
+import React, { Component } from 'react';
|
|
|
+import PropTypes from 'prop-types';
|
|
|
+
|
|
|
+function getEmptyValue(type) {
|
|
|
+ if (type === 'text') {
|
|
|
+ return '';
|
|
|
+ }
|
|
|
+ if (type === 'number') {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ return null;
|
|
|
+}
|
|
|
+
|
|
|
+function makeEmptyFields(docFields) {
|
|
|
+ return Object.keys(docFields).reduce((items, key) => ({
|
|
|
+ ...items,
|
|
|
+ [key]: getEmptyValue(docFields[key].type)
|
|
|
+ }), {});
|
|
|
+}
|
|
|
+
|
|
|
+export default class AddCrudItem extends Component {
|
|
|
+ static propTypes = {
|
|
|
+ docFields: PropTypes.object.isRequired,
|
|
|
+ onCreate: PropTypes.func.isRequired
|
|
|
+ };
|
|
|
+
|
|
|
+ constructor(props) {
|
|
|
+ super(props);
|
|
|
+
|
|
|
+ this.state = makeEmptyFields(props.docFields);
|
|
|
+
|
|
|
+ this.onFieldChange = Object.keys(props.docFields).reduce((items, key) => ({
|
|
|
+ ...items,
|
|
|
+ [key]: event => {
|
|
|
+ this.setState({
|
|
|
+ [key]: event.target.value
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }), {});
|
|
|
+ }
|
|
|
+
|
|
|
+ onCreate = () => {
|
|
|
+ this.props.onCreate(this.state);
|
|
|
+
|
|
|
+ this.setState(makeEmptyFields(this.props.docFields));
|
|
|
+ };
|
|
|
+
|
|
|
+ render() {
|
|
|
+ const {
|
|
|
+ docFields
|
|
|
+ } = this.props;
|
|
|
+
|
|
|
+ const fields = Object.keys(docFields).map(key => (
|
|
|
+ <input key={key}
|
|
|
+ type={docFields[key].type}
|
|
|
+ value={this.state[key]}
|
|
|
+ onChange={this.onFieldChange[key]}
|
|
|
+ />
|
|
|
+ ));
|
|
|
+
|
|
|
+ return (
|
|
|
+ <div className="add-field-wrapper">
|
|
|
+ <div className="fields">
|
|
|
+ {fields}
|
|
|
+ </div>
|
|
|
+ <button className="button-add" onClick={this.onCreate}>{'Add'}</button>
|
|
|
+ </div>
|
|
|
+ );
|
|
|
+ }
|
|
|
+}
|
|
|
+
|