How can I print multiiple text areas when clicking on a button in reactjs

Viewed 47

Within my reactjs class component, I want to create a button that opens a new text area everytime I click on it (e.g., when I click 5 times on it, it should open 5 textareas). In the current result, it only opens a textarea ones.

Thus, In a first step, I created a state with value 0 and create a function that should change the state:

// InitialState
  state = {
    value: 0,
  };

onChange() {
    this.setState({
      value: this.state.value + 1,
    });
  }

In the next step, I rendered a button and created if-statements to show the textareas (which does not work):

render() {
    return (
      <div>
        <IconButton onClick={this.onChange.bind(this)}>
          <AddCircleOutlineIcon />
        </IconButton>
        <br />
        {this.state.value >= 1 ? this.showTextArea() : null}
      </div>
    );
  }

And this is my showTextArea function:

showTextArea = () => {
    return (
      <textarea
        placeholder={this.state.placeholder}
        value={this.state.value}
        onChange={this.onChange1.bind(this)}
        rows="2"
        style={{ fontSize: "18px" }}
        onFocus={(e) => (e.target.placeholder = "")}
        onBlur={(e) => (e.target.placeholder = this.state.placeholder)}
      />
    );
  };
2 Answers

You condition is wrong. this.state.value >= 1 It should be like this because after first textbox opens and you click your button value will be 2 and first textbox will hide

This can be achieved using only single condition. Change your render method like this with for loop:

render() {
    return (
        <div>
            <IconButton onClick={this.onChange.bind(this)}>
                <AddCircleOutlineIcon />
            </IconButton>
            <br />
            {
                for (let i = 0; i < this.state.value; i++) {
                    {this.showTextArea()}
                }
            }
        </div>
    );
}
Related