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

An example of a component is one that allows a user to enter their mailing address. It can render inputs for street, city, state, and postal code. It can contain logic to verify that the postal code matches the city.

Components in non-trivial Svelte applications need to communicate with each other. For example, a 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 that address.

There are many ways for Svelte components to communicate. The table below 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

5.2  Props

5.2.1  Props go in with export

5.2.2  Directives

5.2.3  bind directive on form elements

5.2.4  bind:this

5.2.5  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

sitemap