2

Suppose I have a react component with a controlled form input, ex:

const MyInputs = () => {
  const [val, setVal] = useState("")

  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {
    setVal(event.target.value)  // what is event.target.value here?
  }

  return (
    <form>
      <input value={val} />
    </form>
  )
}

My understanding is that, since I provide no onChange handler to the input, the input box in the browser will not show any keystrokes. I can type all I want but nothing will ever show up in the input box.

Contrast this with a regular, vanilla HTML <input value="something" />. Typing characters in the input box will result in characters appearing on screen and changes to the value attribute of the input.

  1. Is React 'intercepting' change events on controlled components to actively prevent the input's value from changing on keyboard input?

  2. if the value of the controlled input can only change in response to changes to component state, how is it that event.target.value can provide us with "the current text that the user has entered"?

  3. If React does intercept events per Q1, are these handlers overridden by event handlers that I manually attach to a controlled input's onChange attribute?

  4. what is the difference (in terms of browser behavior) between "displaying characters that a user typed in a vanilla html input field" and "re-rendering as a result of component state changes (caused by user keyboard input)"?


EDIT

I understand that value in <input value=... /> is not the same as $myInputElement.value. But The value attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the HTMLInputElement value property in JavaScript..

Aaron Parisi
  • 464
  • 7
  • 15
  • As of my knowledge in a controlled form input, the `event.target.value` represents the current value entered by the user. When no `onChange` handler is provided, React does not intercept change events, and the input behaves like a regular HTML input. With an `onChange` handler, React updates the state, preventing direct value changes based on user keystrokes. – Anandhu Remanan Jun 01 '23 at 05:35
  • Also, The `event.target.value` provides the current input as each keystroke triggers the handler. Manually attaching an onChange handler overrides React's default behavior. In vanilla HTML inputs, characters are directly displayed, while controlled components re-render due to state changes, updating the input's value. Controlled components provide control, validations, and synchronization between UI and state. – Anandhu Remanan Jun 01 '23 at 05:36
  • @AnandhuRemanan I do not think the input behaves like a "regular HTML input" when no onChange handler is passed - typing in such a controlled input results in no characters appearing on screen – Aaron Parisi Jun 01 '23 at 15:20

0 Answers0