I am new to React and got a problem. I got a big a object that will contain a lot of logic for the application I am trying to build.
Based on this object I am trying to render inputfields and also update the corresponding records in the object. I got a Codesandbox with my problem setup here.
I got my 'top level' component that holds the object and passes it down to its children:
import "./styles.css";
import { useState } from "react";
import Content from "./Content";
export default function App() {
const [formDocument, setFormDocument] = useState({
document: {
content: {
sections: [
{
additionalFields: true,
destroyable: false,
key: "personalDetails",
moveable: false,
fields: [
{
fieldType: "text",
key: "name",
linkedFieldsKey: "name"
},
{
fieldType: "text",
key: "emailAddress",
linkedFieldsKey: "emailAddress"
}
]
}
],
records: [{ key: "1", values: ["Tim", "[email protected]"] }]
}
}
});
const updateDocument = (e) => {
//how do I update the corresponding records for the inputfields?
console.log("inputfield is updated");
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Content {...formDocument} updateDoc={(e) => updateDocument(e)} />
</div>
);
}
Now I got a child that uses the formDocument object called Content.jsx and I want to update the corresponding records in the formDocument object. This is the Content.jsx:
export default function Content({ updateDoc, ...formDocument }) {
return (
<div>
<input
style={{ display: "block", marginTop: "10px" }}
type="text"
value={formDocument.document.content.records[0].values[0]}
onChange={(e) => updateDoc(e)}
/>
<input
style={{ display: "block", marginTop: "10px" }}
type="text"
value={formDocument.document.content.records[0].values[1]}
onChange={(e) => updateDoc(e)}
/>
</div>
);
}
How do I update the correct records without making a function for each and every inputfield?