3 Creating components

 

This chapter covers

  • Creating Svelte components
  • Styling Svelte components
  • Implementing logic in Svelte components
  • Defining and updating state in Svelte components

In this chapter we will delve deeper into defining components by creating .sveltefiles. These files specify the JavaScript that implements state and logic, the HTML to be rendered, and the CSS that will style them.

Components are the fundamental building blocks of web applications in most frameworks. Components are composed of closely related portions of a user interface. They can encapsulate data that is specific to their part of the UI, often referred as state. They split a UI into potentially reusable parts.

Some components represent entire pages while others are used within pages. For example, a page that displays a shopping list can be implemented by a ShoppingList component, and it can render each item in the list using an Item component.

Components accept data passed to them from other components using props. These have a syntax similar to HTML attributes, but their values can be any JavaScript type.

The state of a component is the data that is unique to each component instance. The logic of a component is defined by a set of functions that specify its behavior and include event handling.

3.1 Content of .svelte files

3.2 Component markup

3.3 Component names

3.4 Component styles

3.5 CSS specificity

3.6 Scoped vs. global styles

3.7 Using CSS preprocessors

3.8 Component logic

3.9 Component state

3.10 Reactive statements

3.11 Module context

3.12 Building a custom component