@composi/runtime:

Composition

One Program in Another

As a program becomes more complex, so will its view. This may require breaking it down into smaller pieces, even storing those in separate files so they can be reused. The nature of functional components makes it easy to compose them together, passing props from parent to child. You can learn more about functional component composition in the section about the @composi/core render function.

Sometimes composition with function components is not enough. May find that you want children with their own state management. This means they need to be separate programs that you can use instide a parent program. There are several ways in which you can do this:

When composing programs, the child program's view cannot render the component, it has to just return its markup. That way the parent component's view will handle rendering the child's view. Notice how we do this in the following example:

See the Pen @composi/core + runtime Composition1a by Robert Biggs (@rbiggs) on CodePen.

Parent to Child Communication

We can use similar techniques to have the parent change the default state of a child program. The following example shows how we do that with a simple effect that gets passed to the child. Notice that the counter program has its state set to 22. But the parent overrides that value to 123.

See the Pen @composi/core + runtime Composition3a by Robert Biggs (@rbiggs) on CodePen.

Child to Parent Communication

Using the same pattern we used in the previous example, we have an example of the child program using an effect to communicate with the parent.

See the Pen @composi/core + runtime Composition4a by Robert Biggs (@rbiggs) on CodePen.

Strategies for Composition

When planning to use program composition, there are a couple of things to be aware of. The first is that the child component should not render its view. It should just return it.

Handling state between a child and parent takes some planing. In our previous examples the parent is using the state of the child. But if the parent has its own state, then the child's state will need to be added to the parent's state as a property. And when the child component is rendered in the parent, the parent will need to pass the part of its state that corresponds to what the child expects.

Handling effects is fairly straightforward. The parent needs to hijack the child's update method. Doing so, it can allow the child to send a message that gets captured by the parent, or it can hijack the child's update function so that it can send a message to the child.

In general it makes sense to use functional components for most composition requirements. However, there will be situations where a child needs to have its own state. In that case, make it a separate runtime program and use the technique discussed here.

Downloads

You can download examples of composition from Github.