-
Notifications
You must be signed in to change notification settings - Fork 3
Dynamic lists of child components
Often you'll need to manage variably-sized lists of a common component type, or of several potential component types. A collection can take care of the instantiation of list items automatically.
First, register a component type with the collection:
function MyComponent(sources) {
// ...
}
const list = Collection(MyComponent);
Now we can add, remove and update items in the list. This example is based around managing a dynamic list of people, and assumes the existence of an action$
stream which emits items of {action: 'add|remove', person: {id, sources?}}
.
Note that, in most cases, replacing a specific collection item with a new component instance should be an uncommon occurrence, as it's less efficient than simply updating the component via the component's source streams. As such, usually we'll want to pass in a custom sources
object containing a prepared props$
stream, and simply emit new props
objects when a component's properties change.
function updateList(list, {action, person}) {
switch(action) {
case 'add': return list.set(person.id, person.sources);
case 'remove': return list.remove(person.id);
default: return list;
}
}
const people$ = action$
.scan(updateList, Collection(Person))
.skipRepeatsWith(Collection.isEqual);
Notice the static Collection.isEqual
method we've used above, which checks the underlying immutable data structure for equality so that unnecessary processing can be avoided if nothing has changed. There is also a static Collection.areItemsEqual
method if you only want to check for changes in the list of child items and ignore changes to the list of component definitions, which would trigger inequality in Collection.isEqual
.
- [Managing child components](Managing child components)
- [Replacing a child component when state changes](Replacing a child component when state changes)
- [Combining multiple sinks from child components](Combining multiple sinks from child components)
- [Simple merging of a common sink to a derivative stream](Simple merging of a common sink to a derivative stream)
- [Dynamic lists of child components](Dynamic lists of child components)
- [Managing lists of components that don't have a key](Managing lists of components that don't have a key)
- [Handling multiple component types in a single list](Handling multiple component types in a single list)
- [Taking control of a component's lifecycle within a list](Taking control of a component's lifecycle within a list)
API Reference
- [Quick Reference](API Quick Reference)
- [Detailed Reference](API Detailed Reference)