import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Field from 'components/Field';
import FieldView from 'components/FieldView';
import './style.scss';
export default class CrudField extends Component {
static propTypes = {
field: PropTypes.string.isRequired,
pending: PropTypes.bool,
type: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
onEditStart: PropTypes.func.isRequired,
onEditEnd: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.state = {
editing: false,
editValue: props.value
};
}
onChange = event => {
this.setState({
editValue: event.target.value
});
};
onEditStart = () => {
this.setState({
editing: true
});
};
onEditEnd = () => {
if (this.state.editValue !== this.props.value) {
this.props.onEditEnd(this.props.field, this.state.editValue);
}
this.setState({
editing: false
});
};
componentDidUpdate(prevProps) {
if (prevProps.value !== this.props.value) {
this.setState({
editing: false,
editValue: this.props.value
});
}
}
render() {
const {
pending,
type,
value
} = this.props;
if (this.state.editing) {
return (
);
}
const className = classNames('crud-field', {
'multi-line': type === 'textarea',
'single-line': ['text', 'number'].includes(type),
pending
});
return (
);
}
}