Reader small image

You're reading from  Real-World Svelte

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804616031
Edition1st Edition
Languages
Right arrow
Author (1)
Tan Li Hau
Tan Li Hau
author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau

Right arrow

Composing Components

As your application grows, cramming all the logic into a single component becomes impractical. You’ll need to split your app into smaller, modular components and assemble them to form a more complex application.

In this chapter, we’ll explore various techniques to combine components effectively. We’ll start by examining how to inject custom content into a component using slots. Then, we’ll discuss how to conditionally render different HTML elements within a component. We’ll also delve into recursive components, useful for displaying nested or hierarchical data.

We’ll guide you through each topic with hands-on examples, ensuring the techniques you learn are both practical and applicable in real-world scenarios. By the end of this chapter, you’ll have a richer set of strategies to compose components in your Svelte applications.

In this chapter, you will learn the following:

  • Manipulating how a child...

Technical requirements

All the code in this chapter can be found at https://github.com/PacktPublishing/Real-World-Svelte/tree/main/Chapter04.

Manipulating how a child component looks

When you’re combining multiple components, you’ll need to manage how each child component appears and behaves. Even though a child component handles its own display and logic, it still offers controls to tweak its appearance and behavior. From the perspective of the parent component, you’ll want to coordinate these child components to achieve the desired overall functionality.

In this section, we’ll explore various ways to control the look of child components, ranging from the most to the least commonly used methods. Understanding these options will equip you with the tools to make your components both versatile and effective.

The list of options to control how the child component looks includes the following:

  • Controlling through props: This is perhaps the most straightforward way to influence the behavior and appearance of a child component. By passing props from a parent component to a child, you can...

Passing dynamic content through slots

When building complex applications, one size doesn’t always fit all. Balancing between a component’s modularity and a component’s flexibility for customization is crucial.

Take a generic Card component, for example. You might sometimes want to include special headlines, unique lists, or custom footers for specific use cases. It’s nearly impossible to anticipate every requirement, so it’s essential to design components that are both modular and maintainable, yet still open to customization.

This is where Svelte’s slot feature shines. Slots enable you to inject dynamic content into your components, making them incredibly versatile. Instead of designing a Card component that tries to include every possible feature, aim for a simple, clean base that can be enhanced through composition. This approach allows you to piece together more complex, customized components as your needs evolve.

In a Svelte component...

Rendering different HTML element or component types

In any dynamic application, there comes a time when you need even more flexibility than what static components or elements offer. What if you don’t know the type of element or component you’ll need to render until runtime?

Let’s imagine that you’re building a form generator, and the type of form field – whether it’s <Input>, <Checkbox>, or <Select> – is determined by dynamic data. How could you switch between these components seamlessly, especially when they share the same set of props?

One straightforward approach is to use Svelte’s {#if} blocks to conditionally render the component you need. Here is an example code snippet:

<script>
  import Input from './Input.svelte';
  import Checkbox from './Checkbox.svelte';
  import Select from './Select.svelte';
  let type = "input...

Creating recursive components for recursive data

A recursive data structure is a data structure that is defined in terms of itself, meaning that it can be composed of smaller instances of the same type of structure. Recursive data is everywhere – think of a comment section where replies can have their own sub-replies, or a filesystem with nested folders. Creating a component to display them in a frontend application can be challenging.

Imagine we have a variable called folder, which is an array containing either files or additional folders. In this example, the folder variable could look like this:

const folder = [
  { type: 'file', name: 'a.js' },
  { type: 'file', name: 'b.js' },
  { type: 'folder', name: 'c', children: [
    { type: 'file', name: 'd.js' },
  ]},
];

Currently, our folder variable is two levels deep. To represent...

Example – a JSON tree viewer

In this section, we will walk you through building a JSON tree viewer component in Svelte. The JSON tree viewer component helps you visualize JSON data in a tree-like format. Along the way, we’ll make use of some of the advanced Svelte features we’ve covered in this chapter, including <svelte:self>, <svelte:component>, and slots.

Before we start, let’s think about what our JSON Tree Viewer should look like and how it should behave. Essentially, a JSON object is made up of key-value pairs, where the values can be either primitives, arrays, or other nested objects. Our goal is to display these key-value pairs in a way that clearly represents the hierarchical structure of the JSON object.

So, let’s create a JsonTree component for our JSON tree viewer:

<!-- filename: JsonTree.svelte -->
<script>
  export let data;
</script>
<ul>
  {#each Object.entries(data)...

The Container/Presentational pattern

As your application scales in complexity, you may find it beneficial to adopt specific design patterns or guidelines to structure components. One such approach is the Container/Presentational pattern, which divides a component into two categories, the Container component and the Presentational component:

  • Container components focus on functionality. They handle data fetching, state management, and user interactions. While they usually don’t render Document Object Model (DOM) elements themselves, they wrap around Presentational components and supply them with data and actions.
  • Presentational components are all about the user interface. They get their data and event-handling functions exclusively through props, making them highly reusable and straightforward to test.

A common scenario where you’ll see this pattern in action is when using a UI component library. In this case, the library’s components serve as...

Summary

In this chapter, we delved into various strategies for component composition in Svelte, each offering its own set of advantages and applicable scenarios. Mastering these techniques will equip you to build Svelte applications that are not only more dynamic but also easier to maintain and scale.

We kicked off by discussing multiple ways to influence a child component. These ranged from controlling props or using Svelte’s context to customizing styles via CSS custom properties, and even dynamically passing content through slots.

Then, we turned our attention to some of Svelte’s special elements. We explored <svelte:element> and <svelte:component> to dynamically render various HTML elements and Svelte components. We also learned about <svelte:self>, which allows a component to reference itself, thereby facilitating the creation of recursive UI structures. We then applied these newfound skills to build a JSON tree viewer as an illustrative example...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Real-World Svelte
Published in: Dec 2023Publisher: PacktISBN-13: 9781804616031
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Tan Li Hau

Tan Li Hau is a frontend developer at Shopee and a core maintainer of Svelte. He has delivered multiple conference talks and workshops on Svelte. Passionate about sharing his knowledge, Li Hau regularly contributes to the community through blog posts, YouTube videos, and books. He aspires to inspire others to explore and learn about Svelte and other modern web technologies.
Read more about Tan Li Hau