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);
value.split(",")to get all the different values in an array?"hasNoComma".split(',')will give you an array with one element"hasNoComma", so that might work as well.<li>elements