I am creating react app just for training purpose. I am not able to set value on form submit button. If I start typing the values are getting store in name and price but when I click submit button it does not set name and price in formData.
If I try to set values in formData.
onChange={(e) => this.setState({formData:{
price: e.target.value
})}
like above then I can not type input field.
You can check I used console to check what is happening.
import React from 'react';
import { Button, Form, Icon, Modal } from 'semantic-ui-react';
export default class ProductForm extends React.Component {
constructor(props) {
super(props);
this.state = {
showCreateForm: false,
addOrdit:false,
id: "",
name: "",
price: "",
formData: {},
record: {}
};
if (props.isAddProduct){
this.state.showCreateForm = props.isAddProduct;
}
else if (props.singleProduct) {
this.state.id = props.singleProduct.product.productId;
this.state.name = props.singleProduct.product.name;
this.state.price = props.singleProduct.product.price;
this.state.record = props.singleProduct.product;
this.state.showCreateForm = props.singleProduct.isEditProduct;
this.state.addOrdit = props.singleProduct.isEditProduct;
console.log(this.state.name)
}else if(props.closeForm){
this.state.showCreateForm = props.closeForm;
}
}
handleSubmit = event => {
event.preventDefault();
if(this.state.addOrdit){
this.setState({
record: {
productId: this.state.id,
name: this.state.name,
price: this.state.price
}
});
this.props.onAddFormSubmit(this.state.record);
}else{
console.log("In submit befor set "+this.state.name)
this.setState({
formData: {
name: this.state.name,
price: this.state.price
}
});
console.log("In submit after set"+this.state.formData)
this.props.onAddFormSubmit(this.state.formData);
}
}
//On cancel button click close form
closeCreateForm = () => {
this.setState({ showCreateForm: false })
this.props.onFormControl();
}
//Open form
openCreateCustomer = () => {
this.setState({ showCreateForm: true })
}
render() {
let formTitle;
let buttonName;
if (this.state.addOrdit) {
formTitle = "Edit Product";
buttonName = "Edit";
} else {
formTitle = "New Product";
buttonName = "Create";
}
return (
<div>
<Modal size='small'
closeOnTriggerMouseLeave={false}
open={this.state.showCreateForm}>
<Modal.Header>
{formTitle}
</Modal.Header>
<Modal.Content>
<Form onSubmit={this.handleSubmit}>
<Form.Field>
<label>Name</label>
<input type="text" placeholder='Name' name="name"
value={this.state.name}
onChange={(e) => this.setState({name: e.target.value})} />
</Form.Field>
<Form.Field>
<label>Address</label>
<input placeholder='Price' name="price"
value={this.state.price}
onChange={(e) => this.setState({price: e.target.value})} />
</Form.Field>
<br />
<Button type='submit' icon labelPosition='right'
floated='right' color='green'>
<Icon name='check'/>
{buttonName}
</Button>
<Button floated='right'
onClick={this.closeCreateForm} color='black'>
Cancel
</Button>
<br />
</Form>
</Modal.Content>
</Modal>
</div>
)
}
}