skip to Main Content

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


  1. 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 the department 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 your handleDepartmentChange function before modifying it. Here’s an updated version of your function:

    const handleDepartmentChange = (companyIndex, departmentIndex, e) => {
      const newCompanies = [...companies];
      const newDepartment = { ...newCompanies[companyIndex].children[departmentIndex] };
      newDepartment.name = e.target.value;
      newCompanies[companyIndex].children[departmentIndex] = newDepartment;
      console.log(newDepartment.name);
      setCompanies(newCompanies);
    };
    

    This should allow you to modify the name property of the department object without encountering read-only errors.
    I hope this help.

    Login or Signup to reply.
    • 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search