0

I am trying to add each value entered in separate input element which is added on clicking "add" button on GUI, into an array.

There is no initial array, so please do not suggest putting index from any mapping of initial array.

Multiple input elements are added when user clicks on add button on GUI, the method subDivs() below explains that.

So I am passing counter value as an index in onChange handler, but this code does not work. Really looking for some productive inputs, maybe I am missing some essential part.

  handleChange(event, index) {
    event.preventDefault();
    let { nameArray } = this.state;
    nameArray[index] = event.target.value;
    this.setState({nameArray}, () => console.log("Array ", nameArray))
  }

addRow() {
    this.setState({ count: this.state.count + 1 })
  };

  subDivs() {
    let count = this.state.count, uiItems = [];
    var { names } = this.state;
    let options2 = names.map(name2 => {
      return { value: name2.name, label: name2.name };
    })
    while (count--)
      uiItems.push(
        <div className="newName" key={this.nextUniqueId()}>
          <div className="input-group mb-3" >
            <input id={count+1} type="text" className="form-control" placeholder="Enter Name"
              onChange={(e) => this.handleChange(e, count+1)}
            />
          </div>
        </div>
      )
    return uiItems;
  }

0

1 Answer 1

1

Might be helpful.

handleChange(event) {
    event.preventDefault();
    let { nameArray } = this.state;
    if (!Array.isArray(nameArray)) nameArray = [];
    nameArray.push(event.target.value);
    this.setState({nameArray}, () => {
      return {
        nameArray
      };
    });
  }

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

6 Comments

This solution does work, but I get each letter typed and added as a separate element in an array like below, how can I just get the final value typed such as "Test" and "Name"
``` Array [ "T" ] Array [ "T", "Te" ] Array(3) [ "T", "Te", "Tes" ] Array(4) [ "T", "Te", "Tes", "Test" ] Array(5) [ "T", "Te", "Tes", "Test", "N" ] Array(6) [ "T", "Te", "Tes", "Test", "N", "Na" ] Array(7) [ "T", "Te", "Tes", "Test", "N", "Na", "Nam" ] Array(8) [ "T", "Te", "Tes", "Test", "N", "Na", "Nam", "Name" ]
There might be some event rather than onChange on which you are confirmed that this is the name that I want to add. Just call the above method on that event.
Like this : onChange={(e) => this.handleChangeHN(e)}
do you mean I should create one method, which captures the current value and the other which adds that value in an array?
|

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.