836

Warning: A component 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.*

Following is my code:

constructor(props) {
  super(props);
  this.state = {
    fields: {},
    errors: {}
  }
  this.onSubmit = this.onSubmit.bind(this);
}

....

onChange(field, e){
  let fields = this.state.fields;
  fields[field] = e.target.value;
  this.setState({fields});
}

....

render() {
  return(
    <div className="form-group">
      <input
        value={this.state.fields["name"]}
        onChange={this.onChange.bind(this, "name")}
        className="form-control"
        type="text"
        refs="name"
        placeholder="Name *"
      />
      <span style={{color: "red"}}>{this.state.errors["name"]}</span>
    </div>
  )
}
Bondolin
  • 2,793
  • 7
  • 34
  • 62
Riya Kapuria
  • 9,170
  • 7
  • 18
  • 32
  • 4
    what is the initial value of `fields` in state? – Mayank Shukla Oct 30 '17 at 09:48
  • 2
    constructor(props) { super(props); this.state = { fields: {}, errors: {} } this.onSubmit = this.onSubmit.bind(this); } – Riya Kapuria Oct 30 '17 at 09:50
  • 2
    Possible duplicate of [React - changing an uncontrolled input](https://stackoverflow.com/questions/37427508/react-changing-an-uncontrolled-input) – Michael Freidgeim May 07 '19 at 03:05
  • I just discovered you can use `useRef` to conditionally set the value to the current input, e.g. `value={amountInputFocused ? amountRef.current?.value : amountState}`. Not sure if this is by design, but it works, and silences the error. – brandonscript Dec 11 '21 at 07:27

28 Answers28

1435

The reason is, in state you defined:

this.state = { fields: {} }

fields as a blank object, so during the first rendering this.state.fields.name will be undefined, and the input field will get its value as:

value={undefined}

Because of that, the input field will become uncontrolled.

Once you enter any value in input, fields in state gets changed to:

this.state = { fields: {name: 'xyz'} }

And at that time the input field gets converted into a controlled component; that's why you are getting the error:

A component is changing an uncontrolled input of type text to be controlled.

Possible Solutions:

1- Define the fields in state as:

this.state = { fields: {name: ''} }

2- Or define the value property by using Short-circuit evaluation like this:

value={this.state.fields.name || ''}   // (undefined || '') = ''
Bondolin
  • 2,793
  • 7
  • 34
  • 62
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • 22
    is there a reason undefined is "uncontrolled" while the latter is "controlled" - what do these mean? – Prashanth Subramanian Mar 19 '19 at 15:24
  • 1
    @PrashanthSubramanian Maybe this could help understand it better. https://reactjs.org/docs/forms.html#controlled-components – rotimi-best Mar 30 '19 at 03:25
  • I don't have any undefined in my state during the change event – Alexey Sh. Apr 10 '19 at 08:03
  • @AlexeySh. can you explain more? didn't get you. – Mayank Shukla Apr 10 '19 at 08:04
  • you did write that input field will get value as:`value={undefined}`. right? I don't have such value. my state already has a value: `this.state = { settings: {accountNumber: ''} }` – Alexey Sh. Apr 10 '19 at 08:07
  • it will get value as undefined in this case: `this.state = { settings: {} }` and accessing `this.state.settings.accountNumber `. are you getting that error? – Mayank Shukla Apr 10 '19 at 09:17
  • @MayankShukla Why React doesn't complain about this: `value={this.state.fields.name || ''}` ? Isn't that value changing also from an uncontrolled `''` to a controlled `this.state.fields.name` ? I know it works! But I have always wondered why it doesn't trigger the same error? Do you know? – cbdeveloper Jun 12 '19 at 16:06
  • 17
    because `''` is a valid string value. so when you change `''` to 'xyz', input type is not changing means controlled to controlled. But in case of `undefined` to `xyz` type will change from uncontrolled to controlled. – Mayank Shukla Jun 14 '19 at 02:55
  • 10
    Thank you this worked for me: `value={this.state.fields.name || ''}` – Abdulbosid Jul 17 '19 at 09:20
  • In my case this doesn't work. Not sure why. But changing `value` to `defaultValue` helped solve the problem. – newguy Nov 05 '19 at 03:30
  • @newguy in that case field will be uncontrolled, not controlled. – Mayank Shukla Nov 05 '19 at 05:54
  • 8
    I didn't know that once the value becomes undefined the input became automatically uncontrolled, Great. Already fix my problem – Adrian Serna Apr 27 '20 at 20:01
  • 1
    short-circuit did the trick. I was setting value field from state as well and even tried setting the field inside state to an empty string but nothing happened. – BitShift May 21 '20 at 03:56
  • 4
    amazing! because i did't see this mentioned in the official docs, or am i blind? link to source please :) – some_groceries Jun 09 '20 at 18:46
  • @Bondolin, but it is also not allowing user to edit textfield – Mansuu.... Oct 29 '20 at 10:05
  • note that this is also true vice versa like if you are setting a state property's default value to undefined. – Vincent Edward Gedaria Binua Jan 07 '21 at 09:40
  • First way is good solution. It is working well. But what to do when you don't know the property values of `fields`? – MsiLucifer Jan 10 '21 at 02:34
  • I don't know what is wrong with this behaviour. why it's a warning – TheEhsanSarshar Jan 13 '21 at 15:59
  • @PrashanthSubramanian A component with 'undefined' state value is considered uncontrolled component because, a controlled component should have its data-type predefined so as to ensure that it can accept the value stored in the state i.e. a radio button cannot accept text input and so on... – Sajid2405 Feb 02 '21 at 18:44
  • 1
    Sometimes, I feel stackoverflow should be declared the official docs for so many great libraries because of people like you who are so great at explanations for a beginners like us. Thank you great sir – ashutosh Feb 08 '21 at 21:44
  • 1
    I finally understand the controlled vs uncontrolled based on your answer. value || '' solved my issue! – BrianLegg Mar 21 '21 at 02:03
  • mayank sukla , bodolin ... you both are ultra genius. Thank You so much... – Fun Tadka Jul 31 '21 at 08:19
  • 1
    FANTASTIC answer! I think FB should consider updating the error, it's absolutely not clear an empty string is considered a value while undefined is not, as JS is strongly dynamic and often an empty string and undefined are treated very similarly.. – Mattia Rasulo Nov 15 '21 at 11:50
  • I have a question. If my field is of type string I can use empty string as default value, if my field is boolean I can use false but if my field is a number (e.g. an input field where the user has to specify his age) I can't put 0 as default value, will be meaningless on user side. How I can avoid that warning ? Because now I have to put undefined and then when the user interact I can change with the value he want (I'm using controlled component to manage my form). – lucataglia Dec 15 '21 at 22:24
120

Changing value to defaultValue will resolve it.

Note:

defaultValue is only for the initial load. If you want to initialize the input then you should use defaultValue, but if you want to use state to change the value then you need to use value. Read this for more.

I used value={this.state.input ||""} in input to get rid of that warning.

blueseal
  • 2,726
  • 6
  • 26
  • 41
MoFoLuWaSo
  • 1,289
  • 1
  • 5
  • 6
  • 7
    Thank you! I came across this problem and the other solutions didn't apply to me, but this solution helped. – PepperAddict Oct 12 '19 at 21:48
  • 1
    you can apply the same answer for functional component also. Example: `value={user || ""}` – fixedDrill Feb 07 '22 at 10:35
  • This one worked for me. I was using my companies special DLS input components and when I changed value to defaultValue for the specific input field, the field stopped resetting and losing state and the problem went away! – Evan Erickson Jan 02 '23 at 15:39
53

Inside the component put the input box in the following way.

<input
    className="class-name"
    type= "text"
    id="id-123"
    value={ this.state.value || "" }
    name="field-name"
    placeholder="Enter Name"
/>
Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
Tabish
  • 1,592
  • 16
  • 13
39

In addition to the accepted answer, if you're using an input of type checkbox or radio, I've found I need to null/undefined check the checked attribute as well.

<input
  id={myId}
  name={myName}
  type="checkbox" // or "radio"
  value={myStateValue || ''}
  checked={someBoolean ? someBoolean : false}
  />

And if you're using TS (or Babel), you could use nullish coalescing instead of the logical OR operator:

value={myStateValue ?? ''}
checked={someBoolean ?? false}
Lynden Noye
  • 981
  • 8
  • 10
33

SIMPLY, You must set initial state first

If you don't set initial state react will treat that as an uncontrolled component

Vaibhav KB
  • 1,695
  • 19
  • 17
23

that's happen because the value can not be undefined or null to resolve you can do it like this

value={ this.state.value ?? "" }
18
const [name, setName] = useState()

generates error as soon as you type in the text field

const [name, setName] = useState('') // <-- by putting in quotes 

will fix the issue on this string example.

Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
14

As mentioned above you need to set the initial state, in my case I forgot to add ' ' quotes inside setSate();

  const AddUser = (props) => {
  const [enteredUsername, setEnteredUsername] = useState()
  const [enteredAge, setEnteredAge] = useState()

Gives the following error

enter image description here

Correct code is to simply set the initial state to an empty string ' '

  const AddUser = (props) => {
  const [enteredUsername, setEnteredUsername] = useState('')
  const [enteredAge, setEnteredAge] = useState('')
Aindriú
  • 3,560
  • 9
  • 36
  • 54
  • 2
    Exactly that was the mistake!! thanks a lot. – sami ullah Jul 24 '21 at 13:16
  • 1
    I was having the same problem only that instead of using an empty string as initial value I was using `undefined`. Switching to an empty string fixed the problem. Thanks – Martin Sep 24 '21 at 13:51
12

Set Current State first ...this.state

Its because when you are going to assign a new state it may be undefined. so it will be fixed by setting state extracting current state also

this.setState({...this.state, field})

If there is an object in your state, you should set state as follows, suppose you have to set username inside the user object.

this.setState({user:{...this.state.user, ['username']: username}})
noone
  • 6,168
  • 2
  • 42
  • 51
  • 1
    As far as I understand it, setState already only overrides fields, so in the first case it should be unnecessary to destructure assign. In the second state it may be necessary since setState will replace a sub-object wholesale. – Kzqai Jun 26 '19 at 20:55
9

Best way to fix this is to set the initial state to ''.

constructor(props) {
 super(props)
  this.state = {
    fields: {
      first_name: ''
    }
  }
  this.onChange = this.onChange.bind(this);
}

onChange(e) {
  this.setState({
    fields:{
     ...this.state.fields,
     [e.target.name]: e.target.value
    }
  })
}


render() {
  return(
    <div className="form-group">
      <input
        value={this.state.fields.first_name}
        onChange={this.onChange}
        className="form-control"
        name="first_name" // Same as state key
        type="text"
        refs="name"
        placeholder="Name *"
      />
      <span style={{color: "red"}}>{this.state.errors.first_name}</span>
    </div>
  )
} 

Then you can still run your checks like if (field) and still achieve the same result if you have the value as ''.

Now since your value is now classified as type string instead of undefined after evaluation. Thus, clearing the error from the console of a big red block .

HeavenlyEntity
  • 153
  • 2
  • 5
6

I am new to reactjs and I am using version 17 of reactjs I was getting this problem

I solved:

Instead of this

const [email, setEmail] = useState();

I added this

const [email, setEmail] = useState("");

In useState function I added quotes to initialize the data and the error was gone.

Adnan Siddique
  • 324
  • 3
  • 9
4

Put empty value if the value does not exist or null.

value={ this.state.value || "" }
  • 1
    Thanks Max! This is the cause of the problem, however, your code snippet will not work for this user as is (`this.state.fields.name` vs `this.state.value`) – amitayh Aug 05 '20 at 05:55
4

If you're setting the value attribute to an object's property and want to be sure the property is not undefined, then you can combine the nullish coalescing operator ?? with an optional chaining operator ?. as follows:

<input
  value={myObject?.property ?? ''}
/>
andromeda
  • 4,433
  • 5
  • 32
  • 42
3

In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.

For example, if you have this state:

state = {
    "a" : "A",
    "b" : "B",
}

If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c whose value is not only undefined on the component's state but the property itself is undefined.

To solve this just make sure to add c into your state and give it a proper initial value.

e.g.,

state = {
    "a" : "A",
    "b" : "B",
    "c" : "C", // added and initialized property!
}

Hope I was able to explain my edge case.

10110
  • 2,353
  • 1
  • 21
  • 37
3

If you use multiple input in on field, follow: For example:

class AddUser extends React.Component {
   constructor(props){
     super(props);

     this.state = {
       fields: { UserName: '', Password: '' }
     };
   }

   onChangeField = event => {
    let name = event.target.name;
    let value = event.target.value;
    this.setState(prevState => {
        prevState.fields[name] =  value;
        return {
           fields: prevState.fields
        };
    });
  };

  render() { 
     const { UserName, Password } = this.state.fields;
     return (
         <form>
             <div>
                 <label htmlFor="UserName">UserName</label>
                 <input type="text" 
                        id='UserName' 
                        name='UserName'
                        value={UserName}
                        onChange={this.onChangeField}/>
              </div>
              <div>
                  <label htmlFor="Password">Password</label>
                  <input type="password" 
                         id='Password' 
                         name='Password'
                         value={Password}
                         onChange={this.onChangeField}/>
              </div>
         </form>
     ); 
  }
}

Search your problem at:

onChangeField = event => {
    let name = event.target.name;
    let value = event.target.value;
    this.setState(prevState => {
        prevState.fields[name] =  value;
        return {
            fields: prevState.fields
        };
    });
};
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
3

Using React Hooks also don't forget to set the initial value.
I was using <input type='datetime-local' value={eventStart} /> and initial eventStart was like

const [eventStart, setEventStart] = useState();
instead
const [eventStart, setEventStart] = useState('');.

The empty string in parentheses is difference.
Also, if you reset form after submit like i do, again you need to set it to empty string, not just to empty parentheses.

This is just my small contribution to this topic, maybe it will help someone.

zrna
  • 565
  • 1
  • 8
  • 20
3

like this

value={this.state.fields && this.state.fields["name"] || ''}

work for me.

But I set initial state like this:

this.state = {
  fields: [],
}
Latief Anwar
  • 1,833
  • 17
  • 27
3

I came across the same warning using react hooks, Although I had already initialized the initial state before as:-

const [post,setPost] = useState({title:"",body:""})

But later I was overriding a part of the predefined state object on the onChange event handler,

 const onChange=(e)=>{
        setPost({[e.target.name]:e.target.value})
    }

Solution I solved this by coping first the whole object of the previous state(by using spread operators) then editing on top of it,

 const onChange=(e)=>{
        setPost({...post,[e.target.name]:e.target.value})
    }
3

The problem occurs even if you set undefined to the value at a previous rendering that happened even before initializing things properly.

The issue went by replacing

value={value}

with

value={(value==undefined?null:value)}
zhulien
  • 5,145
  • 3
  • 22
  • 36
Ruwan Liyanage
  • 333
  • 1
  • 13
2

Warning: A component 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.

Solution : Check if value is not undefined

React / Formik / Bootstrap / TypeScript

example :

{ values?.purchaseObligation.remainingYear ?
  <Input
   tag={Field}
   name="purchaseObligation.remainingYear"
   type="text"
   component="input"
  /> : null
}
2

The reason of this problem when input field value is undefined then throw the warning from react. If you create one changeHandler for multiple input field and you want to change state with changeHandler then you need to assign previous value using by spread operator. As like my code here.

constructor(props){
    super(props)
    this.state = {
        user:{
            email:'',
            password:''
        }
    }
}

// This handler work for every input field
changeHandler = event=>{
    // Dynamically Update State when change input value
    this.setState({
        user:{
            ...this.state.user,
            [event.target.name]:event.target.value
        }
    })
}

submitHandler = event=>{
    event.preventDefault()

    // Your Code Here...
}

render(){
    return (
        <div className="mt-5">
       
            <form onSubmit={this.submitHandler}>
                <input type="text" value={this.state.user.email} name="email" onChage={this.changeHandler} />
                
                <input type="password" value={this.state.user.password} name="password" onChage={this.changeHandler} />

                <button type="submit">Login</button>
            </form>
      

        </div>
    )
}
Muhammad Minhaj
  • 109
  • 1
  • 7
1

Multiple Approch can be applied:

  • Class Based Approch: use local state and define existing field with default value:
constructor(props) {
    super(props);
    this.state = {
      value:''
    }
  }
<input type='text'
                  name='firstName'
                  value={this.state.value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />

  • Using Hooks React > 16.8 in functional style components:
[value, setValue] = useState('');
<input type='text'
                  name='firstName'
                  value={value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />

  • If Using propTypes and providing Default Value for propTypes in case of HOC component in functional style.
 HOC.propTypes = {
    value       : PropTypes.string
  }
  HOC.efaultProps = {
    value: ''
  }

function HOC (){

  return (<input type='text'
                  name='firstName'
                  value={this.props.value}
                  className="col-12"
                  onChange={this.onChange}
                  placeholder='Enter First name' />)

}


khizer
  • 1,242
  • 15
  • 13
1

Change this

  const [values, setValues] = useState({intialStateValues});

for this

  const [values, setValues] = useState(intialStateValues);
Desarrollalab
  • 337
  • 2
  • 5
1

I also faced the same issue. The solution in my case was I missed adding 'name' attribute to the element.

<div className="col-12">
   <label htmlFor="username" className="form-label">Username</label>
        <div className="input-group has-validation">
             <span className="input-group-text">@</span>
                  <input 
                      type="text" 
                      className="form-control" 
                      id="username"
                      placeholder="Username" 
                      required=""
                      value={values.username}
                      onChange={handleChange}
                  />
                  <div className="invalid-feedback">
                      Your username is required.
                  </div>
        </div>
</div>

After I introduced name = username in the input list of attributes it worked fine.

srigu
  • 329
  • 1
  • 5
  • 16
1

For functional component:

const SignIn = () => {

  const [formData, setFormData] = useState({
    email: "",
    password: ""
  });

  
  const handleChange = (event) => {
    const { value, name } = event.target;
    setFormData({...formData, [name]: value });
  };


  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Signed in");
    setFormData({
      email: "",
      password: ""
    });
  };


  return (
    <div className="sign-in-container">
      <form onSubmit={handleSubmit}>
        <FormInput
          name="email"
          type="email"
          value={formData.email}
          handleChange={handleChange}
          label="email"
          required
        />
        <FormInput
          name="password"
          type="password"
          value={formData.password}
          handleChange={handleChange}
          label="password"
          required
        />
        <CustomButton type="submit">Sign in</CustomButton>
      </form>
    </div>
  );
};

export default SignIn;
1

While this might sound crazy, the thing that fixed this issue for me was to add an extra div. A portion of the code as an example:

  ... [Other code] ...
  const [brokerLink, setBrokerLink] = useState('');
  ... [Other code] ...

  return (
    ... [Other code] ...
              <div styleName="advanced-form" style={{ margin: '0 auto', }}>
                {/* NOTE: This div */}
                <div>
                  <div styleName="form-field">
                    <div>Broker Link</div>
                    <input
                      type="text"
                      name="brokerLink"
                      value={brokerLink}
                      placeholder=""
                      onChange={e => setBrokerLink(e.target.value)}
                    />
                  </div>
                </div>
              </div>
    ... [Other code] ...
  );
... [Other code] ...

Was very strange. Without this extra div, it seems react initially rendered the input element with no value attribute but with an empty style attribute for some reason. You could see that by looking at the html. And this led to the console warning..

What was even weirder was that adding a default value that is not an empty string or doing something like value={brokerLink || ''} would result in the exact same problem..

Another weird thing was I had 30 other elements that were almost exactly the same but did not cause this problem. Only difference was this brokerLink one did not have that outer div.. And moving it to other parts of the code without changing anything removed the warning for some reason..

Probably close to impossible to replicate without my exact code. If this is not a bug in react or something, I don't know what is.

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
0

For me, this was the mistake:

<input onChange={onClickUpdateAnswer} value={answer.text}>
  {answer.text}
</input>

As you see, I have passes string into the body of the Input tag,

Fix:

<input onChange={onClickUpdateAnswer} value={answer.text}></input>
Adnan
  • 906
  • 13
  • 30
0

Change value to defaultValue and it will resolve the error in react or in any other framework.

           <input
            // value={mainOrder.property1}
            defaultValue = {mainOrder.property1}
            onChange={(e) =>
              setMainOrder({ ...mainOrder, property1: e.target.value })
            }
          />
ajay negi
  • 1
  • 1