I have designed the following component:
import React, { useState } from "react";
function Search(props) {
const [studentData, setStudentData] = useState({
studentName: "",
joiningDate: "",
});
const onAdd = () => {
const emptyObject = {
name: "",
joiningDate: "",
};
setStudentData(emptyObject);
}
}
};
return (
<div className="my-50 layout-row align-items-end justify-content-end">
<label htmlFor="studentName">
Student Name:
<div>
<input
id="studentName"
name="studentName"
data-testid="studentName"
type="text"
value={studentData.name}
onChange={onRecordUpdate}
className="mr-30 mt-10"
/>
</div>
</label>
</div>
);
}
export default Search;
Issue is that when I try to clear the input fields after entering them in the Residents List using following code in the function "Search"
const emptyObject = {
name: "",
joiningDate: "",
};
setStudentData(emptyObject);
I get the following error. I'm not sure why React is assuming the input label to be uncontrolled as I'm initializing it using state.
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.
in input (at Search.js:88)
in div (at Search.js:87)
in label (at Search.js:85)
in div (at Search.js:84)
in Search (at App.js:35)
in div (at App.js:34)
in div (at App.js:32)
in App (at src/index.js:8)
Can anybody provide any insights?
CodePudding user response:
Seems like you're using studentName
in the initial state and as value for the input and inside emptyObject
just name
. So studentName
will be undefined
and React assumes the uncontrolled component.
I think renaming name
to studentName
will fix your problem.