I have a React component that has some form fields in it:
<TextField
label="Description"
id="description"
value={company.companyDescription}
onChange={updateFormField("companyDescription")}
></TextField>
and a function that updates my company state whenever the values change:
const updateFormField = (property: string) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => ({ ...prev, [property]: event.target.value }))
}
This means that whenever a form field changes I'd like to create a new copy (hence the spread operator) of the old object.
My problem is that company has nested properties in it, like company.location.address:
{
name: "some company",
location: {
address: "some street"
}
// ...
}
Is there a way to refactor the above function to update the nested properties? For example something like:
const updateFormField = (property: string[]) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => ({ ...prev, [...property]: event.target.value }))
}
company[property]?company.nameorcompany.location.address.