2

I have a button which should add text box to a form. However the clicking the button is not displaying any kind of text field. I am just putting the code necessary for the functionality.

this.state = {
   zoneName: "",
   zonedesc: [{zoneName:""}]
}
<Tab.Pane>
   <button style= {addzone} disabled={this.state.disable}
           type="button"
           onClick={this.handleAddZoneInput}
           className="small">
               Add Zone
           </button>
</Tab.Pane>

handleAddZoneInput = () => {            
  this.setState({
      zonedesc: this.state.zonedesc.concat([{ zoneName: "" }])
  });
  console.log(this.state.zonedesc)
  this.zoneTextBox();
}
zoneTextBox = () =>{
      return this.state.zonedesc.map((zone,idx)=>(
        <div className="zoneInput">
            <PtInputConditionTab style = {{width:'80%'}} disabled={this.state.disable} 
             placeholder={`Zone Description`}
            value={zone.zoneName} onChange={this.handleZoneNameChange(idx)}/>
           
        </div>
   ))
  }

The console.log statement in the function handleAddZoneInput shows that the state value of zonedesc keeps increasing as I keep on clicking the button but the text box is not displayed which is mentioned in the function zoneTextBox. This works perfectly fine if I just put {this.zoneTextBox()} below the button tag which will display a single text box on initial page load and keeps adding as I click the button. But I also need to add the first text box on the button click.

4
  • where is your <form> ? Commented Jun 1, 2021 at 3:58
  • I don't have one. Commented Jun 1, 2021 at 4:01
  • oh. you said the textbox would add to a "form" when onClick Commented Jun 1, 2021 at 4:01
  • where is this <Tab.Pane> in constructor?? and second you have to setState on button Click of the returned value to render. Commented Jun 1, 2021 at 4:21

2 Answers 2

1

Initialize the zonedesc as an empty array [], and put {this.zoneTextBox()} below the button tag, this had to be done because only then the input field will be added to DOM.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this works and thanks for the direction of the code. I totally missed it that I haven't initialized the array as empty
0

Rather than having the zoneTextBox function calling there, you can directly have it in the DOM. The zoneTextBox is returning the value but it's returning into the handleAddZoneInput function.

Checkout this Codesandbox : https://codesandbox.io/s/react-playground-forked-2ebgu

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.