What I trying to do is, generate dynamic input and collect all values into an object with dynamic name, so I defined an empty object in state:
constructor() {
super();
this.state = {
setting_value: {}, // our object
setting_append: 0, // define how input will be append
};
}
Then I append first input as default input:
componentDidMount() {
this.handleAppend(); // run this on load
}
In this function I append an input then create an item and add to current object:
handleAppend = () => {
this.setState({
setting_append: this.state.setting_append + 1
});
let name = '';
let obj = this.state.setting_value; // current object
for(let i = 0; i < this.state.setting_append; i++){
name = 'input_' + i;
obj[name] = null;
}
this.setState({
setting_value: obj
})
}
And render like this:
render() {
const InputList = [];
for (let i = 0; i < this.state.setting_append; i++) {
InputList.push(i);
}
...
return (
{InputList && InputList.map(function (El, Index) {
return (
<Col key={Index} md="6">
<Label>input {Index}</Label>
<Input onChange={(e) => {this.handleValues(e, Index)}}/>
</Col>
)
})}
)
<Button onClick={this.handleAppend}>+</Button> // append more input
And this is our change function:
handleValues = (e, row) => {
let value = e.target.value;
let input_name = 'input_' + row;
if(value){
const new_obj = {...this.state.setting_value, ...{ [input_name]: value}}
this.setState({
setting_value: new_obj
});
console.log(new_obj);
}
}
Problem!
Okay, after page load, I got one input, then I type some text and output is (log):
{input_0: 'xxxx'}
Then I click on button to append another input, then type some text:
{input_0: null, input_1: '12'}
it make previous input null but I need this output:
{input_0: 'xxxx', input_1: '12'}
Then if I type some new value on first input, output is:
{input_0: 'sdf'}
But should be:
{input_0: 'sdf', input_1: '12'}
Any idea what I have done wrong?