React: Warn when an input switches between controlled and uncontrolled

Created on 11 Jan 2016  路  7Comments  路  Source: facebook/react

A component should either be using uncontrolled inputs or controlled inputs, but not both (they should pick a single paradigm, for the lifetime of the component). As a result, an instance of an input should never switch from controlled to uncontrolled (or vice versa).

We should warn when an input that was previously controlled becomes uncontrolled, or vice versa.

starter

All 7 comments

@jimfb Could you provide some code as to how a controlled input becomes uncontrolled and vice versa?

I just got this warning, can anyone point me to an explanation with a bit more detail? ty

@newswim put your code in a stackoverflow question, and link it here.

newswim https://fb.me/react-controlled-components

Read about controlled components and uncontrolled components. Choose one (preferably controlled components), and don't ever use uncontrolled components. If you are using controlled components, make sure you never pass a null or undefined to React.

And yes, @brigand is correct, this is better addressed on StackOverflow.

I don't consider an input's value being null or undefined as a qualifying factor in determining if an input is controlled or uncontrolled. Controlled forms are a paradigm that may share some qualities with uncontrolled forms. It's about listening to changes and updating the state of the value, but React shouldn't stipulate that the value can't be undefined. It's an additional burden to those following good practice in using controlled forms.
This warning should occur if both defaultValue and value props are used throughout the input's lifecycle.

It's an additional burden to those following good practice in using controlled forms.

I agree, but in the sense that they shouldn't be a single component at all, they should be two separate. Regardless I would say that actually providing the correct string value to an interactive component that expects a string value seems like a rather good practice. Otherwise you will have two distinct value states null and '', but both being intended to mean the exact same thing.

This warning should occur if both defaultValue and value props are used throughout the input's lifecycle.

No, because value being null or undefined makes it uncontrolled by definition and you shouldn't switch between controlled and uncontrolled.

Was this page helpful?
0 / 5 - 0 ratings