A component is changing an uncontrolled input of type text to be controlled error in ReactJS [Solution] 2022

    By: Manu
    2 years ago

    If you face this component is changing an uncontrolled input error that means value in input is undefined at some point. and we need to add some check to ensure this won't happen

    Here

      const [title, setTitle] = useState();
    
      const updateTitle = (e) => {
        if(e.currentTarget.value !== null && e.currentTarget.value !=='')
        {
          setTitle(e.currentTarget.value); // Here we are setting title value
        }
      }
    
    
    <input type="title" 
                           className="form-control" 
                           id="title"
                           onChange={updateTitle}
                           value={title} /> // here is error comming from
    

    So fix is

    change

     value={title} />
    

    To

     value={title || ""} />
    

    This will fix it.


    or you can correct the check already applied in updateTitle function

      const updateTitle = (e) => {
        if(e.currentTarget.value !== null && e.currentTarget.value).   // Here we are checking for undefined after &&
        {
          setTitle(e.currentTarget.value); // Here we are setting title value
        }
      }
    

    This will also fix it.