Answer the question
In order to leave comments, you need to log in
How to add an element to a form on click in React?
The situation is as follows: the head is boiling, but the work is still the sea.
In the process of studying React, the question arose:
There is a form
"Name Phone"
How, when clicking on something, add another input "Quantity of goods N" to this form, and remove it from the form again?
display: none is not an option, since all this mess will be passed on to the handler, i.e. I need to generate, but I don’t understand how something, but I don’t see it in the documentation. everything is already floating.
Answer the question
In order to leave comments, you need to log in
I sketched an example - jsfiddle.net/yuvuyrhv/19
class MyForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.addGood = this.addGood.bind(this);
this.changeGoodCount = this.changeGoodCount.bind(this);
this.state = { goods: [] };
}
handleSubmit() {
console.log('handleSubmit');
}
addGood() {
const { goods } = this.state;
this.setState({ goods: [ ...goods, { count: 0 } ] });
}
changeGoodCount(n, count) {
const { goods } = this.state;
this.setState({ goods: goods.map( (good, i) => i === n ? { count } : good ) });
}
render() {
const { goods } = this.state;
const { handleSubmit, addGood, changeGoodCount } = this;
console.log('MyForm.render() -> goods =', goods);
return (
<form onSubmit={handleSubmit}>
<div>
Имя пользователя: <input type="text" />
</div>
<div>
Телефон: <input type="text" />
</div>
<div>
{ goods.map( (good, i) => <GoodInput key={i} good={good} n={i} onChange={changeGoodCount}/> ) }
</div>
<div>
<button type="button" onClick={addGood}>Добавить что-либо</button>
</div>
</form>
);
}
}
class GoodInput extends React.Component {
handleChange(e) {
const { n, onChange } = this.props;
const count = e.currentTarget.value;
onChange(n, count);
}
render() {
const { good, n } = this.props;
return (
<div>
Количество товара {n} <input type="text" onChange={(e) => this.handleChange(e)} />
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question