A component is changing an uncontrolled input to be controlled in React
How to solve Warning: A component is changing an uncontrolled input to be controlled in React
This warning typically occurs in React when you have an input element whose value is initially undefined (or null), and then you try to control it by setting its value with state. React warns about this because it can lead to unexpected behavior.
Here's a common scenario where you might encounter this warning:
js
1 const Input = ({ isChecked, setIsChecked }) => {2 return (3 <tr4 className={`${5 i % 2 === 06 ? 'bg-white border-b dark:bg-gray-450 dark:border-gray-500'7 : 'border-b bg-gray-100 dark:bg-gray-500 dark:border-gray-500'8 }`}9 >10 <td className='px-6 py-2 whitespace-nowrap dark:text-white'>11 <div className='flex items-center'>12 <input13 type='checkbox'14 checked={isChecked}15 className='w-4 h-4 text-blue-600 bg-gray-10016 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-217 dark:bg-gray-700 dark:border-gray-600'18 onChange={setIsChecked}19 />20 </div>21 </td>22 </tr>23 );24 };25 export default Input;
In this example, isChecked is initially undefined because useState() is called without an initial value. When the component renders, React sees that the input has no initial value, and it considers it an uncontrolled component. Later, when you update the state with setInputValue, you are attempting to control the input.
To resolve this warning, you can provide a fallback value. For example:
js
1 <input2 type='checkbox'3 checked={isChecked || false}4 className='w-4 h-4 text-blue-600 bg-gray-1005 order-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-26 dark:bg-gray-700 dark:border-gray-600'7 onChange={setIsChecked}8 />