11 Subcomponents—communication via props and

 

This chapter covers

  • Adding a new virtual DOM type to represent components
  • Implementing subcomponents: components inside other components
  • Passing data from a parent component to its children using props
  • Communicating between components using events

What’s the value of a component if it can’t include other components inside it? The Component class you’ve implemented in the previous two chapters can’t return other components from its render() method; it can only return fragments, elements, or text nodes. But as you can imagine, building a complex application using just a single component that renders the entire view is… well, not very practical.

In this chapter, you learn how to add subcomponents (components inside other components) to your framework, and how to communicate between them using props and events. A parent component can pass data to its children using props, and children can communicate with their parents emitting events, as illustrated in figure 11.1.

Figure 11.1. Props flow down, events flow up
ch11 f01 orbaiceta

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).

Figure 11.2. Anatomy of a stateful component
ch11 f02 orbaiceta

In this chapter you’ll add the following private properties to the Component class:

11.1 Adding components as a new virtual DOM type

11.1.1 Updating the elements getter

11.1.2 Mounting component virtual nodes

11.1.3 Destroying component virtual nodes

11.1.4 Patching component virtual nodes

11.1.5 (optional) A rendering optimization

11.2 Events

11.2.1 Saving the event handlers inside the component

11.2.2 Extracting the props and events for a component

11.2.3 Wiring the event handlers

11.2.4 Emitting events

sitemap