I am making a very simple react application that has the basic details as inputs.
I am having these form values in context.
context.js
import React, { useState } from "react";
export const FormContext = React.createContext();
export function FormProvider({ children }) {
const [formValue, setFormValue] = useState({
basicDetails: {
firstName: "John",
lastName: "Doe",
address: {
city: "city",
zip: "zip"
}
}
});
return (
<FormContext.Provider value={[formValue, setFormValue]}>
{children}
</FormContext.Provider>
);
}
In basic details component, I am trying to render the form like,
basicdetails.js
The below code is working fine
<label htmlFor="firstName">First Name: </label>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={basicDetails.firstName}
onChange={(event) => handleInputChange(event)}
/>
The below code is not working
<label htmlFor="lastName">City: </label>
<input
type="text"
id="city"
name="city"
value={basicDetails.address.city}
onChange={(event) => handleInputChange(event)}
/>
Reason:
The second given input lies under nested object ie.., basicDetails.address.city.
And I am giving the name attribute value as city only.
basicDetails: {
firstName: "John",
lastName: "Doe",
address: {
city: "city",
zip: "zip"
}
}
But the handleInputChange covers only parent level changes.
const handleInputChange = (event) => {
const { name, value } = event.target;
setValue((prev) => {
const basicDetails = { ...prev.basicDetails, [name]: value };
return { ...prev, basicDetails };
});
};
Requirement:
Please kindly help me to update the form that has nested object as well.. basicdetails.address.city .
Note:
Now I am having city and zip but later it may extend and more number of fields will be added to it.. So I cannot hardcode the condition check..