state = {
phones: [
{ id: 1, title: '', number: '' },
],
}
onChange = ({ target: { value, name, dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.map((n, i) => +index === i
? { ...n, [name]: value }
: n
),
}));
}
addPhone = () => {
this.setState(({ phones }) => ({
phones: [
...phones,
{
id: 1 + Math.max(...phones.map(n => n.id)),
title: '',
number: '',
},
],
}));
}
delPhone = ({ target: { dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.filter((n, i) => i !== +index),
}));
}
render() {
return (
<div>
{this.state.phones.map((n, i) => (
<div key={n.id}>
<input name="title" data-index={i} value={n.title} onChange={this.onChange} />
<input name="number" data-index={i} value={n.number} onChange={this.onChange} />
{i ? <button data-index={i} onClick={this.delPhone}>x</button> : null}
</div>
))}
<button onClick={this.addPhone}>Add</button>
</div>
);
}