import React, { Component, } from 'react'; import { Button, FormGroup, Label, Input, InputGroup, InputGroupAddon, Col } from 'reactstrap'; import { FaPlus, } from 'react-icons/fa'; class VegetablesProperties extends Component { constructor(props) { super(props); this.state = { selectedProperties: [], availableProperties: [], selectedPropety: null }; this.handleChange = this.handleChange.bind(this); this.handleArrayChange = this.handleArrayChange.bind(this); this.updateParent = this.updateParent.bind(this); this.addProperty = this.addProperty.bind(this); this.notSet = this.notSet.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.selectedProperties) { this.setState({ selectedProperties: nextProps.selectedProperties }); } if (nextProps.availableProperties) { this.setState({ availableProperties: nextProps.availableProperties, // selectedPropety: (nextProps.availableProperties.length > 0 ? nextProps.availableProperties[0].id : null) }); } } handleChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value, }); } handleArrayChange(e) { const { id, value } = e.target; let { selectedProperties } = this.state; const targetIndex = selectedProperties.findIndex(datum => { return Number(datum.propertyId) === Number(id); }); if (targetIndex !== -1) { selectedProperties[targetIndex].value = value; this.setState({ selectedProperties }); } } addProperty() { for (let i = 0; i < this.state.availableProperties.length; i += 1) { if (this.state.availableProperties[i].id === Number(this.state.selectedPropety)) { this.setState(prevState => ({ selectedProperties: [ ...prevState.selectedProperties, { propertyId: this.state.selectedPropety, value: '', label: this.state.availableProperties[i].name } ] })); break; } } } notSet(propertyId) { let isSet = false; for (let i = 0; i < this.state.selectedProperties.length; i += 1) { if (this.state.selectedProperties[i].propertyId === propertyId) { isSet = true; break; } } return !isSet; } updateParent() { this.props.setProperties({ target: { type: 'text', name: 'Properties', value: this.state.selectedProperties } }); } render() { return (
{this.state.selectedProperties.map( (item , key) => ( ))}
{this.state.availableProperties.map( (item, key) => { if ( this.notSet( item.id ) ) { return () } return (null) })}
) } } export default VegetablesProperties;