I have an input field in React.
<input
type = "number"
value = {this.props.answer || undefined}
onKeyUp = {(e) => (e.keyCode === 13) ? onAnswer(e.target.value) : false }
/>
This way it behaves just like I need it to behave:
- If there is no
this.props.answer
there is no inital value in the input. - User can input any number. Nothing happens on
onChange
- Once user presses Enter, the state changes (in the
onAnswer
function). After this, the value of the input field staysthis.props.answer
and the user can NOT change the value any more.
But when the user presses Enter I get this warning:
A component is changing an uncontrolled input of type number to be controlled.
I read about uncontrolled components and I tried this:
<input
type = "number"
defaultValue = {this.props.answer || undefined}
ref={this.input}
onKeyUp = {(e) => (e.keyCode === 13) ? onAnswer(e.target.value) : false }
/>
This way I doesn't get the warning but the input field remains editable after the user presses Enter. I also tried using both value
and defaultValue
properties but then again I get the same warning.
I want the input field to be sort of controlled but I don't want to change the state on onChange
but only when user presses Enter (onKeyUp
). After this, the user should not be able to edit the input. Is there a way to implement this behavior?
UPDATE: I wasn't aware that I can set the readOnly
property of the input based on the state. Setting it to false after setting the state solves my problem.
disabled
orreadonly
state instead? – rickdenhaanreadonly
. It just solve my problem. Thanks! – Tahin Dánielreadonly
property solved my issue. – Tahin Dániel