chapter five

5 Component communication

 

This chapter covers:

  • Passing data into components using props
  • Getting data out of components by binding to props
  • Using slots to supply content to be rendered
  • Dispatching events to notify parent elements
  • Using context to pass data to descendant components

Components in non-trivial Svelte applications need to communicate with each other.

For example, suppose we have a component that allows a user to enter their mailing address. It can render inputs for street, city, state, and postal code. It also contains logic to verify that the postal code matches the city. Another component that displays a map may want to know when the data in our mailing address component has been changed so it can display the location of the new address.

There are many ways for Svelte components to communicate. Table 5.1 summarizes the available options. It uses the terms “parent,” “child,” “descendant,” and “ancestor” to refer to the relationships between components in the component hierarchy.

Parent components directly render child components in their HTML sections. Ancestor components can be one or more levels removed from their descendant components. For example, if a Bank component renders an Account component, which renders a Transaction component, the Bank component is an ancestor of the Transaction component, and the Transaction component is a descendant of the Bank component.

5.1  Component communication options

5.2  Props

5.2.1  Props go in with export

5.2.2  Reacting to prop changes

5.2.3  Prop types

5.2.4  Directives

5.2.5  The bind directive on form elements

5.2.6  bind:this

5.2.7  Props go out with bind

5.3  Slots

5.4  Events

5.4.1  Event dispatching

5.4.2  Event forwarding

5.4.3  Event modifiers

5.5  Context

5.6  Building the Travel Packing app

5.7  Summary