class Bills extends Component {
constructor(props) {
super(props)
this.state = {
productName: '',
price: 0,
quantity: 0,
noOfProductsField: 0
}
}
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
createFields = () => {
const { classes } = this.props;
let children = []
for (let i = 0; i < this.state.noOfProductsField; i++) {
children.push(
<div>
<Select
className={classes.textField}
value = { this.state[i] }
onChange={this.handleChange('productName')}
displayEmpty
SelectProps={{
MenuProps: {
className: classes.menu,
}
}}>
<MenuItem value="" disabled>
Select Product
</MenuItem>
{this.state.products.map((option, ind) => (
<MenuItem key={ind} value={option.productName}>
{option.productName}
</MenuItem>
))}
</Select>
<TextField className={classes.textField} placeholder='Price' type='number' onChange={this.handleChange('price')} />
<TextField className={classes.textField} placeholder='Quantity' type='number' onChange={this.handleChange('quantity')} />
</div>
)
}
return children
}
}
I Have this function which is creating 3 input fields in for loop
- productName
- price
- quantity
For Example if loop is running 2 times it will create 6 fields like image below:
So now i want to manage state for all 6 fields differently How can i do that ?
You need to create dynamic form inputs right? So what you can do is you can pass the name of the product to you handler
this.handleChange('productName')
and then you can do something like following. In your case you will need to use computed property name so as to dynamically set the state(like you are already doing)Or you can create seperate onChange handlers each for product, price, quantity.
Quick flow: When product onChange occurrs you can store the product in the procucts array(in state) and when price change will occure you can send the product name along with it and map the product with price and quantity.
Here you can find a nice JS bin replica with React, of exact same thing you want to achieve.
you can create dynamic select field using react js
demo >> codepen
You can add
name
attribute to each input component and make one handler method which get the name as an argument.You can read more about how to handle multiple inputs on React docs.