2

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)} />
3
  • Do you want to check comma in event.target.value ? Commented Oct 8, 2019 at 10:27
  • Yes, sorry I should have explained that - will edit. Commented Oct 8, 2019 at 10:29
  • If you want to check comma in event.target.value you can use if (event.target.value.indexOf(',') > -1) { event.target.value.split(',') } Commented Oct 8, 2019 at 10:31

2 Answers 2

3

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.

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

2 Comments

Perfect and very nice elegant solution! Will mark correct when the timer allows.
You might want to check if event.target.value has a value (is not empty ''). This will happily add "".
1

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] ]
        }
    }))
}

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.