3

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)}
      />
    );
  };
Rainer Winkler
  • 485
  • 1
  • 7
  • 20

2 Answers2

3

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

Alim Öncül
  • 127
  • 2
  • 14
1

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>
    );
}
Yogendra Chauhan
  • 805
  • 5
  • 15
  • ok, thanks. But still, when I change this code, it only opens my text area ones. Can you identify any other mistake, maybe it is in my showTextArea() function that looks as following: `showTextArea = () => { return ( – Rainer Winkler Aug 12 '20 at 06:35
  • @RainerWinkler you need to run a loop on state value to draw no of text areas. see edited example above. – Yogendra Chauhan Aug 12 '20 at 06:47
  • 1
    Ok, thank you so much, this already helps a lot. It seems that react render does not allow for functions but uses map functions instead. I will have a look how this works. – Rainer Winkler Aug 12 '20 at 07:39