import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Field from 'components/Field'; import './style.scss'; function getEmptyValue(type) { if (type === 'text' || type === 'textarea') { 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 => (