Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding Input form field issue reactjs

I am trying to add one cascaded form(inner) field dynamically on click of a button +Add Content. The array for the field is getting updated but the view is still same.

However, when I try to add the outer field on click of a button +Add Heading dynamically its getting added with no issues. Below is the stackblitz url for reference. Thanks in advance.

https://stackblitz.com/edit/react-utjwsu?embed=1&file=index.js

like image 959
richa singh Avatar asked Jan 02 '19 14:01

richa singh


2 Answers

You're only ever rendering one Content field, and the {this.AddContentInput} isn't valid syntax. You can edit the AddContentBox method to render all of the Content fields:

Original:

...
<FormGroup>
    <Label className="set-label-pos upload-img" for="Heading">Content</Label>
    <input className="form-control" type="text"/>
</FormGroup>
{this.AddContentInput}
...

Replaced with:

...
{ this.AddContentFields(element) }
...

and

AddContentFields(element) {
  return element.Content.map(content => {
    return (
      <FormGroup>
        <Label className="set-label-pos upload-img" for="Heading">Content</Label>
          <input className="form-control" type="text"/>
        </FormGroup>
    );
  })
}

Here's an edited version of the app with my changes: https://stackblitz.com/edit/react-lcy2te

like image 179
dan Avatar answered Sep 28 '22 04:09

dan


Your code is working fine and the state is updating perfectly. The problem is that the Content part is added only once in your code. I just used a function which you already added in it

{this.addContentTextBox(element.Content)}

Just replace the AddContentBox function with this:

AddContentBox(){
        return this.state.content.map((element,i)=>(
            <div className="header-content" key={i} >
                <div className="heading-content-wrapper">
                <FormGroup>
                <Label className="set-label-pos upload-img" for="Heading">Heading</Label>
                <input className="form-control" type="text"/>
                </FormGroup>
                {this.addContentTextBox(element.Content)}
                {this.AddContentInput}
                <FormGroup>
                <Button color="success" onClick={this.AddContentInput.bind(this,i)}>+ Add Content</Button>
                </FormGroup>
            </div>
            </div>
        ))
    }

You have the code in that file, but i think you forgot to add it in the function.

Hope it helps :)

like image 21
Thinker Avatar answered Sep 28 '22 04:09

Thinker