0

I am trying to use the same inputbox for entering different values so each time when the values is entered i should store the value and display to the user .<input type="text" onChange={e => this.addPrice('input1', e.target.value)} /> this is placed inside the modal so whenever the modal popup is open use will enter the value

3
  • Can you add some more code making the question more clear? Right now it says you are using the same input box. But there is no mention of code showing where you are using it. Commented Jul 24, 2018 at 14:40
  • Does the user press a button (or perform another action) to store the value? Currently the this.addPrice in the onChange will be triggered for every character added to the input Commented Jul 24, 2018 at 14:42
  • addPrice=(input, value)=>{this.setState({amount:value}) how can i store the different value entered in a same array or how to differentiate the values Commented Jul 24, 2018 at 14:45

1 Answer 1

1

In order to use the same input box to add values to a single array, there will most likely have to be a secondary action (like pressing a button) that the user takes to indicate when to store the current value.

state = {
  currentValue: '',
  prices: [],
}

onChange = (event) => {
  this.setState({ currentValue: event.target.value })
}

addPrice = () => {
  this.setState(prevState => ({
    prices: [...prevState.prices, this.state.currentValue]
  }))
}

...

<input type='text' onChange={this.onChange} value={this.state.currentValue} />
<button onClick={this.addPrice}>Add Price</button>

Edit: You can store anything in the prices array. If you want key-value pairs then store objects like:

addPrice = () => {
  this.setState(prevState => ({
    prices: [...prevState.prices, {amount: this.state.currentValue}]
  }))
}
Sign up to request clarification or add additional context in comments.

4 Comments

then while opening the input box again will result with the display of previous values since we are using value={this.state.currentValue}
You can add a method to clear the currentValue upon opening or closing the input box.
well said one more question can i set any key for the value while storing in an array like [key:'',value:'']
You can store whatever you want in the array, but it sounds like you want to store objects. I'll update the answer to address that.

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.