Sometimes, we want to fix React input defaultValue doesn’t update with state with JavaScript.
In this article, we’ll look at how to fix React input defaultValue doesn’t update with state with JavaScript.
How to fix React input defaultValue doesn’t update with state with JavaScript?
To fix React input defaultValue doesn’t update with state with JavaScript, we can update the key value when the defaultValue updates.
For instance, we write
<input defaultValue={myVal} key={myVal} />;
in our component to set the defaultValue prop to myVal to set the default value of the input.
And we set the key prop to the same value so that when myVal changes, the key prop changes, which will trigger the input to re-render.
Conclusion
To fix React input defaultValue doesn’t update with state with JavaScript, we can update the key value when the defaultValue updates.