Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this component switching from controlled to uncontrolled? - React

Tags:

reactjs

redux

Here is my stateless react component:

export default ({acresMin, update}) => (
    <div>
        <input
            onChange={(e) => update({'acresMin': e.target.value})}
            placeholder="10"
            type="text"
            value={acresMin}/>
    </div>
)

When I change the value in the input, I get this warning:

Warning: StatelessComponent is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

I am updating with an onChange and saving the value in the store which is being populated through the props.

What do I not understand about this?

like image 846
jhamm Avatar asked Jun 18 '16 17:06

jhamm


People also ask

How do you fix a component is changing an uncontrolled input to be controlled?

The warning "A component is changing an uncontrolled input to be controlled" occurs when an input value is initialized to undefined but is later changed to a different value. To fix the warning, initialize the input value to an empty string, e.g. value={message || ''} .

What's the difference between a controlled component and an uncontrolled one in React?

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

Why we use controlled and uncontrolled components?

Controlled component is component that get the changed value from the callback function and uncontrolled component is component that have the one from the DOM. For example, When input value is changed,we can use onChange function in Controlled Component and also we can get the value using DOM like ref.

Can a component be both controlled and uncontrolled?

A single value within a component's data set (props and state), can be either controlled or uncontrolled, but not both. A single component can, however, have a mixture of controlled and uncontrolled values.


1 Answers

Uncontrolled input does not refer to your component directly, but to the input field that is defined in your component.

React differentiates between controlled and uncontrolled components:

An <input> without a value property is an uncontrolled component

Is your acresMin property undefined when you first render the component? This would cause the input to be renderd as an uncontrolled one at first, but as a controlled one later once the property is set.

like image 142
TimoStaudinger Avatar answered Sep 21 '22 14:09

TimoStaudinger