Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Create dynamic input and store values on object with dynamic name

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!