react runtime_error ai_generated true

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value.

ID: react/controlled-uncontrolled-input-switch

Also available as: JSON · Markdown · 中文
92%Fix Rate
87%Confidence
1Evidence
2023-11-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
[email protected] active
[email protected] active

Root Cause

An input element's value prop transitions from undefined (uncontrolled) to a defined value (controlled) or vice versa during a re-render, causing React to switch modes unexpectedly.

generic

中文

输入元素的 value 属性在重新渲染期间从未定义(不受控制)变为已定义值(受控制),或反之,导致 React 意外切换模式。

Official Documentation

https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable

Workarounds

  1. 95% success Initialize the state variable to an empty string instead of undefined, and always pass a string to the value prop.
    Initialize the state variable to an empty string instead of undefined, and always pass a string to the value prop.
  2. 85% success If the value can legitimately be null/undefined, use defaultValue for the initial uncontrolled state and then switch to controlled with a key prop to remount the input.
    If the value can legitimately be null/undefined, use defaultValue for the initial uncontrolled state and then switch to controlled with a key prop to remount the input.

中文步骤

  1. Initialize the state variable to an empty string instead of undefined, and always pass a string to the value prop.
  2. If the value can legitimately be null/undefined, use defaultValue for the initial uncontrolled state and then switch to controlled with a key prop to remount the input.

Dead Ends

Common approaches that don't work:

  1. Adding a default value to the input via defaultValue prop while keeping value undefined 85% fail

    defaultValue is only for uncontrolled inputs; mixing it with a value prop that later becomes defined still triggers the warning.

  2. Using a ternary operator to conditionally set value to undefined or a string 90% fail

    This creates the exact flip-flop between undefined and defined that causes the warning.

  3. Setting the input's value to an empty string by default to avoid undefined 40% fail

    While this avoids the warning, it may not reflect the intended initial state (e.g., null for optional fields), leading to incorrect UX.