Reputation: 1582
I need some help designing a React app singe page app.
I want to show and let the user edit (via form inputs) a complex JSON structure (with known shape), but I'm having trouble picturing how to bind the values in my generated form to the data structure. The JSON structure is static, I just want to let the user edit values, not the structure itself.
Some of the values depend on other values in the structure (e.g. the max value of a field is specified in other field). The data has nested structures but they do not map 1:1 to my components (I don't control the input) which makes handling more complex (deep components can change surface values).
For example purposes:
data.json
{
"age": 12,
"maxAge": 100,
"name": {
"first": "John",
"last": "Doe"
},
"dogName": "Foo"
}
main.jsx
ReactDOM.render(<Editor data={data} />, mount);
Editor.jsx
<form>
<Person data={props.data} />
<Text defaultValue={props.data.dogName} />
<h2>Settings:</h2>
<Number defaultValue={props.data.maxAge} />
</form>
Person.jsx
<fieldset>
<Text defaultValue={props.data.name.first} />
<Text defaultValue={props.data.name.last} />
<Number max={props.data.maxAge} defaultValue={props.data.age} />
</fieldset>
Handling each and every field manually with change events seems too complex, tiresome (I have tens of fields per component), and error-prone... and I'm not even sure how to propagate the changes to the top-level component from the inner ones.
What are the alternatives?
Upvotes: 2
Views: 1721
Reputation: 715
For an official guide: Thinking in React
I believe the above guide can help walk you through some of the challenges that you are facing.
For your first point: I would use state to hold the information. You can do "two way" data binding to have the form represent your data and the data represent your form. You can also use some form of onChange function calls to update the data that relies on other inputs.
Section 5 of the linked guide goes over propagating data up the chain (ie person -> editor) using callbacks.
If this is going to potentially evolve into a larger project, I would suggest looking into Flux for a MVC type front end with React as the View.
Upvotes: 2