Button click not rendering Input Field on React

Viewed 160

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.

2 Answers

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.

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

Related