1

I have a input box that accepts user input and stores it as a string in an array. I want to be able to parse a pasted string in the input box, like Value 1, Value 2, Value 3. And have those values parsed then added separately to the array, (e.g) ["Value 1", "Value 2", "Value 3"]

There's probably a lot of different ways to do this, but I was looking at Papaparse and it certainly seems like a viable solution.

I could use some help on how to integrate this into my change handler that adds these values to the array.

I have a sandbox example that shows the current setup.

How can I parse a user entered list of values separated by a comma, and have each value added to an array while also displaying the value in a <li> element?

import React from "react";
import ReactDOM from "react-dom";
import Papa from "papaparse";

const list = "Value1 , value2, value3";
var results = Papa.parse(list);

class App extends React.Component {
  state = {
    selectorValues: [],
    selectorValue: ""
  };

  addSelectorValue = e => {
    e.stopPropagation();
    e.preventDefault();
    this.setState(prevState => ({
      selectorValues: [...prevState.selectorValues, prevState.selectorValue],
      selectorValue: ""
    }));
  };

  removeSelectorValue(index) {
    this.setState({
      selectorValues: this.state.selectorValues.filter((_, i) => i !== index)
    });
  }

  handleSelectorValueChange = ({ target: { value } }) => {
    //makes separate copy of array.
    this.setState({ selectorValue: value });
  };

  render() {
    const { selectorValues } = this.state;

    return (
      <div>
        <form>
          <div>
            <label>Selector Values:</label>{" "}
            <input
              type="text"
              value={this.state.selectorValue}
              placeholder="Enter selector value"
              onChange={this.handleSelectorValueChange}
              required={!this.state.selectorValues.length}
            />
            <button type="button" onClick={this.addSelectorValue}>
              Add
            </button>
          </div>
          <ul>
            {this.state.selectorValues.map((value, index) => {
              return (
                <li key={index}>
                  {value}
                  <button
                    type="button"
                    onClick={this.removeSelectorValue.bind(this, index)}
                  >
                    Remove
                  </button>
                </li>
              );
            })}
          </ul>
        </form>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
5
  • 1
    What is the question? Commented Mar 11, 2019 at 16:47
  • Maybe you could use value.split(",") to get all the different values in an array? Commented Mar 11, 2019 at 16:53
  • @Tholle good point, what if there are no commas to act as a delimiter? Basically I want to simplify the process of adding these values, so they don't have to be added one by one, but instead can paste a list into the input box Commented Mar 11, 2019 at 16:55
  • "hasNoComma".split(',') will give you an array with one element "hasNoComma", so that might work as well. Commented Mar 11, 2019 at 16:56
  • 1
    @Tholle split was easy enough to put in there, but visually I can't seem to get the entered values separated and displayed back to the user in the <li> elements Commented Mar 11, 2019 at 17:24

1 Answer 1

2

You could use the string method split to split the selectorValue string up into substrings with , as delimiter and add those to your selectorValues array.

addSelectorValue = e => {
  e.preventDefault();
  this.setState(({ selectorValues, selectorValue }) => ({
    selectorValues: [...selectorValues, ...selectorValue.split(",")],
    selectorValue: ""
  }));
};

class App extends React.Component {
  state = {
    selectorValues: [],
    selectorValue: ""
  };

  addSelectorValue = e => {
    e.preventDefault();
    this.setState(({ selectorValues, selectorValue }) => ({
      selectorValues: [...selectorValues, ...selectorValue.split(",")],
      selectorValue: ""
    }));
  };

  removeSelectorValue(index) {
    this.setState({
      selectorValues: this.state.selectorValues.filter((_, i) => i !== index)
    });
  }

  handleSelectorValueChange = ({ target: { value } }) => {
    this.setState({ selectorValue: value });
  };

  render() {
    const { selectorValues } = this.state;

    return (
      <div>
        <form onSubmit={this.addSelectorValue}>
          <div>
            <label>Selector Values:</label>
            <input
              type="text"
              value={this.state.selectorValue}
              placeholder="Enter selector value"
              onChange={this.handleSelectorValueChange}
              required={!this.state.selectorValues.length}
            />
            <button>
              Add
            </button>
          </div>
          <ul>
            {this.state.selectorValues.map((value, index) => {
              return (
                <li key={index}>
                  {value}
                  <button
                    type="button"
                    onClick={this.removeSelectorValue.bind(this, index)}
                  >
                    Remove
                  </button>
                </li>
              );
            })}
          </ul>
        </form>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

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

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.