Showing different sub-form based on user input
Remember there was a call to this.get_meta_widget?
So again, the advantage of using redux is that it always keep the latest state of the application. By using react-redux, it always re-render the components that receives a different set of properties.
Here is what get_meta_widget does
get_meta_widget() {
let result;
switch (this.props.publication.type) {
case "journal":
result = (
<Journal
delegate_update={this.handle_update}
definition={this.props.publication.meta || {}}
/>
);
break;
case "book":
result = (
<Book
delegate_update={this.handle_update}
definition={this.props.publication.meta || {}}
/>
);
break;
default:
result = "";
}
get_meta_widget() {
let result;
switch (this.props.publication.type) {
case "journal":
result = (
<Journal
delegate_update={this.handle_update}
definition={this.props.publication.meta || {}}
/>
);
break;
case "book":
result = (
<Book
delegate_update={this.handle_update}
definition={this.props.publication.meta || {}}
/>
);
break;
default:
result = "";
}
return result;
}
return result;
}
There you have it, there’s no need to notify the component when the user made changes through the select box (refer to the previous page). As the state changes, the component will re-render itself, and a different component is then inserted into the form automatically.
On the component reuse
So in the publication meta field (refer to the problem statement in the first page, there is another list of people, this time as editors. So we can now insert the Persons component, very similar to what we did with authors previously (in the previous page).
<Persons
delegate_update={this.handle_update}
field="editors"
legend="Editors"
persons={this.props.definition.editors || [{}]}
/>
and the respective handle_update
handle_update(_, changes) {
return this.props.delegate_update(false, {
meta: Object.assign({}, this.props.definition, changes)
});
}
Which is very similar to what we did in other components. It is just the matter of generating a new entity via Object.assign calls, integrate the changes to the parent form through delegate_update property method. Then the child component can generate the new state without having to know what the parent component looks like, then dispatch the new revision to redux.
The complete code can be found at my github repository. Feel free to leave me a comment here or an issue on github so we can discuss further into this.