1
votes

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 stays this.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.

1
If you don't want the user to be able to edit the value, then shouldn't you toggle the disabled or readonly state instead?rickdenhaan
It is unclear what you are trying to do. Can you take a step back and explain? Do you want to make the form read-only once submitted?Davin Tryon
@rickdenhaan I didn't know about readonly. It just solve my problem. Thanks!Tahin Dániel
@DavinTryon It's not really a form just an input field but yes, I need to make it read only after user presses Enter and the state changes. But setting the readonly property solved my issue.Tahin Dániel

1 Answers

0
votes

You can prevent the input from being edited in the keyUp event handler:

onKeyUp = (e) => {
   // Check if we still accept typing
   if (no_more_typing) return e.preventDefault();
   // Handle enter key
   if (e.keyCode === 13) onAnswer(e.target.value);
}

<input
  onKeyUp={onKeyUp} ...