Reputation: 1
react_devtools_backend.js:4026 Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. code:
import React, { useState } from "react";
const App = () => {
const [state, setState] = useState({ name: "bilal", password: "1234" });
const handlrChange = (e) => {
setState(e.target.name);
};
return (
<div>
<form>
<label>
Name:
<input
type="text"
name="name"
value={state.name}
onChange={handlrChange}
/>
</label>
<label>
password:
<input
type="text"
name="password"
value={state.password}
onChange={handlrChange}
/>
</label>
</form>
</div>
);
};
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
enter code here
Upvotes: 0
Views: 132
Reputation: 1645
First of all know that Controlled Components are those whoose changes are handled by React application and Un-Controlled are those whoose is handled by DOM itself. Now, your state has 2 values in it. On first render everything is alright and both of the input fields are controlled ones. But once you will change any one of it, consider in your handler your are not setting the value for both the state variables and thus one of them will become uncontrolled ( i.e will be handled by DOM) and react will then send the warning to you.
Solution is to change the whole state on handler as:
const handlrChange = (e) => {
setState({...state, [e.target.name]: e.target.value});
};
Upvotes: 1