Skip to content

Instantly share code, notes, and snippets.

@Franckapik
Last active January 24, 2020 21:41
Show Gist options
  • Save Franckapik/80dd41f8b7bb305eea47663f3c27a814 to your computer and use it in GitHub Desktop.
Save Franckapik/80dd41f8b7bb305eea47663f3c27a814 to your computer and use it in GitHub Desktop.
import React, {Component} from 'react';
class AddProduct extends Component {
constructor(props) {
super(props);
this.state = {
cart: [""],
prix: '',
nom: '',
qte: 1,
sousTotal: '',
reduction: '',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const name = event.target.name;
if (name === "produitId") {
this.setState({
prix: this.props.produits[event.target.value].prix,
nom: this.props.produits[event.target.value].nom
});
} else {
this.setState({[name]: event.target.value});
}
}
appendInput() {
let produit = {
prix : this.state.prix,
quantite : this.state.qte,
name : this.state.nom,
reduction : this.state.reduction,
sous_total : this.state.qte * this.state.prix
}
this.setState({ cart: [...this.state.cart, produit]})
}
render() {
return (<div>
<form>
<div id="dynamicInput">
{
this.state.cart.map((p, i) => {
return (<div>
<p key={i} className="flex_r">
<label>
Produit {i}
<select name="produitId" onChange={this.handleChange}>
{
this.props.produits.map((n, a) => {
return (<option value={a}>{n.nom}</option>)
})
}
</select>
</label>
<label>
Quantité
<input name="qte" value={this.state.prix} onChange={this.handleChange}/>
</label>
<label>
Prix
<input name="prix" value={this.state.prix} onChange={this.handleChange}/>
</label>
<label>
Sous-total
<input name="sousTotal" value={this.state.qte * this.state.prix} onChange={this.handleChange}/>
</label>
<i className="fas fa-plus-circle" onClick={() => this.appendInput()}> Valider</i>
</p>
</div>);
})
}
</div>
<label>
Réduction
<input name="reduction" value={this.state.reduction} onChange={this.handleChange}/>
</label>
</form>
<button onClick={() => this.appendInput()}>
Add product
</button>
</div>);
}
}
export default AddProduct
@Franckapik
Copy link
Author

I would like to make a cart with a form and dynamic input...
When i submit the form, a product is added to the cart with the appendInput function. Next, a new input for a new product is generated.
But the problem is on the value in the input. When i change the new input, the old one is changed to because the inputs value are value=this.state.blabla ...
is there a way to look at the state for the new input generated, and look for the data in the cart in state for the old one, validated ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment