Reputation: 207
This is my code:
const [defaultBuy, setDefaultBuy] = useState({
data: '',
price: 0
})
const changeBuyPrice = (e: any) => {
let value = e.target.value
if (value > 1000) {
value = 9000
}
console.log(value)
setDefaultBuy({...defaultBuy, price: value})
}
And this is render:
<input defaultValue={defaultBuy.price} name="" type="text" onChange={(e) => changeBuyPrice(e)} />
If I put number larger than 1000
in input, console.log(value)
show me 9000
.
But <input>
tag not show 9000
.
I want to change <input>
value also
Upvotes: 0
Views: 19261
Reputation: 488
At the end, I did e.target.value = value to update the value of the input field
const changeBuyPrice = (e: any) => {
let value = e.target.value
if (value > 1000) {
value = 9000
}
console.log(value)
setDefaultBuy({...defaultBuy, price: value})
e.target.value = value // add this here to update your input field
}
Upvotes: 1
Reputation: 943671
If you want the input to reflect the value in the state then you need to make it a controlled component.
Assign the value in the state to the value
prop instead of the defaultValue
prop.
Upvotes: 3