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
1 Answer
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}]
}))
}
4 Comments
pageNotfoUnd
then while opening the input box again will result with the display of previous values since we are using value={this.state.currentValue}
chrisbot
You can add a method to clear the
currentValue upon opening or closing the input box.pageNotfoUnd
well said one more question can i set any key for the value while storing in an array like [key:'',value:'']
chrisbot
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.
this.addPricein theonChangewill be triggered for every character added to the input