I use this handleDepartmentChange to change the input value when updating.
const handleDepartmentChange = (companyIndex, departmentIndex, e) => {
const newCompanies = [...companies];
newCompanies[companyIndex].children[departmentIndex].name = e.target.value;
console.log(newCompanies[companyIndex].children[departmentIndex].name);
setCompanies(newCompanies);
};
For that I use the following way
<div style={{ display: "flex" }}>
<input
style={{ width: "410px" }}
type="text"
//defaultValue={department.name}
value={department.name}
onChange={(e) =>
handleDepartmentChange(companyIndex, departmentIndex, e)
}
/>
</div>
```
but this dont allow me to chage the value of department it say its read only property? why? is there any other method or way around to fix this Issue?
2
Answers
The error message "read-only property" indicates that the
department
object you are trying to modify is defined as a read-only property in your code. This can happen for various reasons, such as if thedepartment
object was passed down as a prop from a parent component and is not intended to be modified by the current component.To fix this issue, you can create a copy of the
department
object in yourhandleDepartmentChange
function before modifying it. Here’s an updated version of your function:This should allow you to modify the
name
property of thedepartment
object without encountering read-only errors.I hope this help.
This is happening because of you have written something like this in
your Input tag.
value={department.name}
Input tag value attribute make the value fix for that attribute. You
can’t change the value of that input after giving attribute value.
After that you will unable to write anything in that input field.
So remove the value attribute.
To fix this you can go for default value as you have mentioned in
your tag. Default value allows to modify input field’s value.
defaultValue={department.name}
May be It will solve your issue…Let me know if not…Thank you!