Reputation: 3228
I have a state object with a nested array of objects called "axisLabels".
If the user is to enter anything into the input, I want to check if there is a comma (comma separated) within event.target.value of the input to update the second object within the array.
How is this possible?
My current function code updates both.
State obj:
selectedTemplateData: {
axisLabels: ['Option 1', 'Option 2']
}
function to update array:
axisChange(event) {
event.persist();
this.setState(prevState => ({
selectedTemplateData: {
...prevState.selectedTemplateData,
Axislables: [event.target.value, event.target.value]
}
}))
}
Usage:
<input type="text" onChange={(event) => this.axisChange(event)} />
Upvotes: 2
Views: 1347
Reputation: 2922
Here you'll find other examples, but a simple way to do it is the following:
axisChange(event) {
event.persist();
const e = event && event.target && event.target.value;
const values = e && e.split(',').length > 1
? e.split(',')
: e;
this.setState(prevState => ({
selectedTemplateData: {
...prevState.selectedTemplateData,
Axislables: [ values[0], values[1], values[n] ]
}
}))
}
Upvotes: 1
Reputation: 67296
This would certainly work:
axisChange(event) {
event.persist();
this.setState(prevState => ({
selectedTemplateData: {
...prevState.selectedTemplateData,
Axislables: [...event.target.value.split(',')]
}
}))
}
If there is no comma, the value will be preserved. If there is a comma, you can split the values and spread them into the new array.
Upvotes: 3