11 Subcomponents: Communication via props and events
This chapter covers
- Adding a new virtual DOM type to represent components
- Implementing subcomponents
- Passing data from a parent component to its children using props
- Communicating among components by using events
What’s the value of a component if it can’t include other components? The Component
class that you implemented in chapters 9 and 10 can’t return other components from its render()
method; it can return only fragments, elements, or text nodes. But, as you can imagine, building a complex application by using a single component that renders the entire view isn’t very practical.
In this chapter, you learn how to add subcomponents (components inside other components) to your framework and how to communicate among them by using props and events. A parent component can pass data to its children by using props, and children can communicate with their parents by emitting events, as illustrated in figure 11.1.
Figure 11.1 Props flow down; events flow up.
Let’s briefly review the “Anatomy of a stateful component” diagram from chapter 9 and the annotated properties and methods you’ll implement in this chapter (figure 11.2).