Successfully added
React
by Patrik
How to Auto-Fill a Field Only When Empty in React
When building forms in React, sometimes you want one field to copy values from another field — but only if it is still empty. For example, you may want a mediaContentUrl
field to auto-fill with the same value a user types in another field.
A common problem is that after the first letter, the mediaContentUrl
field is no longer "empty," so it stops updating. The trick is to keep syncing while it matches the other field, and stop once the user edits it directly.
Here’s a simplified fix you can use inside your change handler:
setFormValues(prev => {
const updated = { ...prev, [name]: value, mediaFile: null };
// Only sync if mediaContentUrl is empty
// or still the same as the field being typed
if (name !== "mediaContentUrl") {
const prevField = String(prev[name] ?? "");
const prevMedia = String(prev.mediaContentUrl ?? "");
if (!prevMedia || prevMedia === prevField) {
updated.mediaContentUrl = value;
}
}
return updated;
});
This way, the mediaContentUrl
field will auto-fill until the user changes it, and then it stops syncing.
react
forms
javascript
frontend
state
Referenced in:
Comments