React is giving me this warning for two of my input elements.
react-dom.development.js:86 Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
However, in my implementation I'm currently using onKeyDown rather than onChange to achieve essentially the same thing. See my current implementation below:
function Example() {
const [value, setValue] = useState("");
return (
<main>
// ...
<input type="text" onKeyDown={handleKeyDown} value={value} />
// ...
</main>
);
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "enter") return handle() // Must be called on enter press, cannot use onChange for this as that triggers when the element is clicked away from
if (e.key.length === 1) return setValue(value + e.key); // input is not case-sensitive so no need to check for shift key or caps lock
if (e.key === "Backspace") {
if (e.ctrlKey) return setValue("");
else return setValue(value.slice(0, -1);
}
}
I understand it would prefer I use onchange, but that removes the ability to handle on pressing enter. Whilst it's an option to simply write both onChange and onKeyDown, doesn't this overcomplicate for no reason?
Can I safely ignore this issue? Is there a way of suppressing just this error message so I don't have to deal with it whilst building/debugging with the console open? Should I simply set the input field to readonly (my current implementation still works, at least on chrome)?
Edit: I've defined the input as readOnly to prevent this issue. It's not exactly a very good solution as it means the keyboard won't pop up for on-screen-keyboards (not a priority to support mobile browsers as a mobile app is planned) but it seems to be the only way to resolve this effectively.