"," "," Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words
in menus or dialog boxes appear in bold. Here is an example: “When you have a
element,
by default when you hit the Submit button, it will navigate to the location indicated by the action
attribute, carrying along with it the value filled in the elements within the element.”"," Tips or important notes"," Appear like this."," Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you have found a mistake in this book, we would be grateful if you would report this to us. Please
visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would
be grateful if you would provide us with the location address or website name. Please contact us at
[email protected] with a link to the material.
\f xvii","If you are interested in becoming an author: If there is a topic that you have expertise in and you
are interested in either writing or contributing to a book, please visit authors.packtpub.com.","Share Your Thoughts","Once you’ve read Real-World Svelte, we’d love to hear your thoughts! Please click here to go straight","to the Amazon review page for this book and share your feedback.","Your review is important to us and the tech community and will help us make sure we’re delivering","excellent quality content.","\fxviii"," Download a free PDF copy of this book"," Thanks for purchasing this book!"," Do you like to read on the go but are unable to carry your print books everywhere?"," Is your eBook purchase not compatible with the device of your choice?"," Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost."," Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical"," books directly into your application."," The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content"," in your inbox daily"," Follow these simple steps to get the benefits:"," 1. Scan the QR code or visit the link below"," https://packt.link/free-ebook/9781804616031"," 2. Submit your proof of purchase"," 3. That’s it! We’ll send your free PDF and other benefits to your email directly","\f Part 1: Writing Svelte"," Components","In this section, we will lay the foundation for writing Svelte components. We will kick things off by
delving into the lifecycles of Svelte components. Then, we will learn how to style and theme our Svelte
components. After that, we will explore the intricacies of data passing between components and finally
wrap up with techniques to compose components into a cohesive Svelte application.
This part has the following chapters:"," • Chapter 1, Lifecycles in Svelte"," • Chapter 2, Implementing Styling and Theming"," • Chapter 3, Managing Props and State"," • Chapter 4, Composing Components","\f\f 1"," Lifecycles in Svelte","Svelte is a frontend framework. You can use Svelte to build websites and web applications. A Svelte","application is made up of components. You write a Svelte component within a file with .svelte","extension. Each .svelte file is one Svelte component.","When you create and use a Svelte component, the component goes through various stages of the","component lifecycle. Svelte provides lifecycle functions, allowing you to hook into the different stages","of the component.","In this chapter, we will start by talking about the various lifecycles and the lifecycle functions in","Svelte. With a clear idea of lifecycles in mind, you will then learn the basic rule of using the lifecycle","functions. This is essential, as you will see that this understanding will allow us to use the lifecycle","functions in a lot of creative ways.","This chapter contains sections on the following topics:"," • What are Svelte lifecycle functions?"," • The rule of calling lifecycle functions"," • How to reuse and compose lifecycle functions","Technical requirements
Writing Svelte applications is very easy and does not require any paid tools. Despite the added value
of most paid tools, we decided to use only free tools to make the content of this book available to you
without any limitations.
\f4 Lifecycles in Svelte"," You will require the following:"," • Visual Studio Code as the integrated development environment (https://code."," visualstudio.com/)"," • A decent web browser (Chrome, Firefox, or Edge, for instance)"," • Node.js as the JavaScript runtime environment (https://nodejs.org/)"," All the code examples for this chapter can be found on GitHub at: https://github.com/
PacktPublishing/Real-World-Svelte/tree/main/Chapter01
Code for all chapters can be found at https://github.com/PacktPublishing/Real-
World-Svelte."," Understanding the Svelte lifecycle functions"," When using a Svelte component, it goes through different stages throughout its lifetime: mounting,"," updating, and destroying. This is similar to a human being. We go through various stages in our lifetime,"," such as birth, growth, old age, and death, throughout our lifetime. We call the different stages lifecycles."," Before we talk about lifecycles in Svelte, let’s look at a Svelte component.","
"," Can you tell me when each part of the code is executed?"," Not every part of the code is executed at once; different parts of the code are executed at different"," stages of the component lifecycle."," A Svelte component has four different lifecycle stages: initializing, mounting, updating, and destroying.","\f Understanding the Svelte lifecycle functions 5","Initializing the component","When you create a component, the component first goes through the initialization phase. You can","think of this as the setup phase, where the component sets up its internal state.","This is where lines 2–7 are being executed.","The count variable is declared and initialized. The onMount, beforeUpdate, afterUpdate,","and onDestroy lifecycle functions are called, with callback functions passed in, to register them at","the specific stages of the component lifecycles.","After the component is initialized, Svelte starts to create elements in the template, in this case, a","

Updated {updateCount} times","To reuse all the logic of the counter: – the counting of update cycles and the starting and stopping
of the measurement – we should move all of it into a function, which ends up looking like this:","


Updated {$updateCount} times","The update counter returns an object that contains the updateCount variable and the
startMeasuring and stopMeasuring functions.
The implementation of the createUpdateCounter function is left as an exercise to you, and
you can check the answer at https://github.com/PacktPublishing/Real-World-
Svelte/tree/main/Chapter01/01-update-counter.
We’ve learned how to extract a lifecycle function and reuse it, so let’s take it up a notch and reuse
multiple lifecycle functions in the next pattern: composing lifecycle functions.","Composing lifecycle functions into reusable hooks","So far, we’ve mainly talked about reusing one lifecycle function. However, there’s nothing stopping us","from grouping multiple lifecycle functions to perform a function.","Here’s an excerpt from the example at https://svelte.dev/examples/update. The example","shows a list of messages. When new messages are added to the list, the container will automatically","scroll to the bottom to show the new message. In the code snippet, we see that this automatic scrolling","behavior is achieved by using a combination of beforeUpdate and afterUpdate:","
"," To reuse this autoscroll logic in other components, we can extract the beforeUpdate and
afterUpdate logic together into a new function:"," export function setupAutoscroll() {","   let div;","   let autoscroll;","   beforeUpdate(() => {","     autoscroll = div && (div.offsetHeight + div.scrollTop) > (div."," scrollHeight - 20);","   });","   afterUpdate(() => {","     if (autoscroll) div.scrollTo(0, div.scrollHeight);","   return {","   setDiv(_div) {","   div = _div;","     },","   };"," }"," We can then use the extracted function, setupAutoScroll, in any component:","
"," In the refactored setupAutoscroll function, we return a setDiv function to allow us to update"," the reference of the div used within the setupAutoscroll function."," As you’ve seen, by adhering to the one rule of calling lifecycle functions during component initialization,"," you can compose multiple lifecycle functions into reusable hooks. What you’ve learned so far is sufficient"," for composing lifecycle functions, but there are more alternatives on the horizon. In the upcoming"," chapters, you’ll explore Svelte actions in Chapter 5 and the Svelte store in Chapter 8, expanding your"," options further. Here’s a sneak peek at some of these alternatives.","\f Coordinating lifecycle functions across components 15","An alternative implementation could be to make div a writable store and return it from the
setupAutoscroll function. This way, we could bind to the div writable store directly instead
of having to call setDiv manually.
Alternatively, we could return a function that follows the Svelte action contract and use the action
on the div:"," export function setupAutoscroll() {","   let div;","   // ...","   return function (node) {","     div = node;","     return {","       destroy() {","         div = undefined;","       },","     };","   };"," }","setupAutoscroll now returns an action, and we use the action on our div container:","
","We will discuss the Svelte action contract in more detail later in the book.
We’ve seen how we can extract lifecycle functions into a separate file and reuse it in multiple Svelte
components. Currently, the components call the lifecycle functions independently and function as
standalone units. Is it possible to synchronize or coordinate actions across components that uses the
same lifecycle functions? Let’s find out.","Coordinating lifecycle functions across components","As we reuse the same function across components, we can keep track globally of the components that","use the same lifecycle function.","Let me show you an example. Here, I would like to keep track of how many components on the screen","are using our lifecycle function.","\f16 Lifecycles in Svelte"," To count the number of components, we can define a module-level variable and update it within our
lifecycle function:"," import { onMount, onDestroy } from 'svelte';"," import { writable } from 'svelte/store';"," let counter = writable(0);"," export function setupGlobalCounter() {","   onMount(() => counter.update($counter => $counter + 1));","   onDestroy(() => counter.update($counter => $counter - 1));","   return counter;"," As the counter variable is declared outside the setupGlobalCounter function, the same
counter variable instance is used and shared across all the components.
When any component is mounted, it will increment the counter, and any component that is referring
to the counter will get updated with the latest counter value.
This pattern is extremely useful when you want to set up a shared communication channel between
components and tear it down in onDestroy when the component is being destroyed.
Let’s try to use this technique in our next exercise."," Exercise 2 – Scroll blocker"," Usually, when you add a pop-up component onto the screen, you want the document to not be"," scrollable so that the user focuses on the popup and only scrolls within the popup."," This can be done by setting the overflow CSS property of the body to \"hidden\"."," Write a reusable function used by pop-up components that disables scrolling when the pop-up component"," is mounted. Restore the initial overflow property value when the pop-up component is destroyed."," Do note that it is possible to have more than one pop-up component mounted on the screen at once,"," so you should only restore the overflow property value when all the popups are destroyed."," You can check the answer at https://github.com/PacktPublishing/Real-World-"," Svelte/tree/main/Chapter01/02-scroll-blocker."," Summary
In this chapter, we went through the lifecycles of a Svelte component. We saw the different stages of a
component lifecycle and learned when the lifecycle function callbacks will be called.
We also covered the rule of calling lifecycle functions. This helps us to realize the different patterns
of reusing and composing lifecycle functions.
In the next chapter, we will start to look at the different patterns for styling and theming a Svelte component.
\f 2
Implementing
Styling and Theming
Without styling, an h1 element within a component will look the same as another h1 element from
another component. Svelte allows you to use Cascading Style Sheets (CSS), a language used for styling
and formatting web content, to style your elements, giving them a different look and feel.
In this chapter, we will start by talking about different ways to style a Svelte component. We will then
see some examples, including integrating a popular CSS framework, Tailwind CSS, into Svelte.
Following that, we will talk about themes. When you have a set of styles consistently applied throughout
Svelte components, you’ll see an overall styling theme in your components. We will talk about how to
synchronize the styles across components, as well as how to let users of the components customize them.
By the end of the chapter, you will have learned various methods of styling and will be comfortable in
choosing the right approach and applying the right methods, depending on the scenario.
This chapter includes sections on the following:"," • Ways to style a Svelte component"," • Ways to style a Svelte component with Tailwind CSS"," • Applying themes to Svelte components","Technical requirements
You can find the code used in this chapter on GitHub: https://github.com/PacktPublishing/
Real-World-Svelte/tree/main/Chapter02.
\f18 Implementing Styling and Theming"," Styling Svelte components in six different ways"," In a Svelte component, you have elements that define the structure and content. With styling, you can"," change the look and feel of the elements beyond the browser default."," Svelte components can be styled in six different ways. Let’s explore the different ways to apply a style"," to elements within a Svelte component."," Styling with the style attribute"," Firstly, you can add inline styles to an element with the style attribute:","
"," The preceding snippet will turn the color of the text within div to blue.
Similar to the style attribute in HTML elements, you can add multiple CSS styling declarations:","
"," The syntax of adding multiple CSS styling declarations in Svelte is the same as you would do in HTML.
In the preceding snippet, we change the text within div to be blue in color and 2 rem in size.
The value of the style attribute is a string. You can form the style attribute with dynamic expressions:","
"," Sometimes it gets messy when you have multiple CSS styling declarations within the style attribute:","
"," Using style: directives"," Svelte provides style: directives, which allow you to split the style attribute into several attributes,"," which is hopefully more readable after adding line breaks and indentations:","   style:color={color}
  style:font-size={fontSize}
  style:background={background}
  style:border-top={borderTop}
/>"," The style: directive follows the following syntax:"," style:css-property-name={value}
\f Styling Svelte components in six different ways 19","The CSS property name can be any CSS property, including CSS custom properties:","
","And if the name of the style matches the name of the value it depends on, then you can use the
shorthand form of the style: directive:","   style:color
  style:font-size={fontSize}
  style:background
  style:border-top={borderTop}
/>","A style declared in the style: directive has higher priority than the style attribute. In the following
example, the h1 text color is red instead of blue:","
","Besides adding inline styles to style an element one by one, the next approach allows us to write CSS
selectors to target multiple elements and style them together.","Adding the ","This approach is useful when you want to apply the same style across multiple elements within
the component.
In the preceding code, would the CSS rule turn all the div elements in the document to blue?
No. The CSS rules within the "," Whenever an element matches the selector, the Svelte compiler will generate a CSS class name that
is unique to the component and apply it to the element. At the same time, Svelte limits the scope of
the elements being selected by the CSS rule by including a class selector of the generated class name
in the selector.
The transformation of the element and the CSS rule looks like this:","
row

"," Here, \"svelte-g5jdbb\" is the unique CSS class name that is generated by calculating the hash
value of the CSS content. The hash value will be different when the CSS content changes. Since the
Svelte compiler only applies the CSS class name to the elements within the component, it is unlikely
that the style will be applied to other elements outside the component.
This transformation happens during compilation by default. There’s nothing additional that you need
to do. The example here is more for illustration purposes only.
Knowing that the CSS rules within the ","The value of the class attribute can be a string or a dynamic expression.","You can conditionally apply classes to the element:","
","In the preceding example, when the value of both toHighlight and toBold is true, the class
attribute value evaluates to \"highlight bold\". Thus, two classes, highlight and bold, are
applied to the div element.
This pattern of conditionally applying classes to an element based on a variable is so common that
Svelte provides the class: directive to simplify it.","Simplifying the class attribute with the class: directive","In the previous example, we conditionally applied the highlight class when the toHighlight","variable was truthy, and bold when the toBold variable was truthy.","This can be simplified with the class: directive, where you have the following:"," class:class-name={condition}","To simplify the previous example with the class: directive, we have the following:","
","Just like the style: attribute, you can further simplify to a class: directive shorthand if the name
of the class is the same as the name of the variable for the condition.
\f22 Implementing Styling and Theming"," If the condition for adding the highlight class is instead a variable named highlight, then the
preceding example can be rewritten as follows:","
"," Putting all of them together, in the following code example, the div element has a yellow background
when the highlight variable is true, and a transparent background otherwise:","

"," All the approaches of applying styles to an element that we’ve explored so far have the CSS declarations
written within the Svelte component. However, it is possible to define styles outside of the Svelte component."," Applying styles from external CSS files"," Let’s say you add a style element to the HTML of your application, like so:","
  
    
  
"," Alternatively, you could include external CSS files in the HTML of your application, like so:","
  
    
  
"," In both cases, the CSS rules written in them are applied globally to all elements in the application,
including elements within your Svelte component.
If you are using build tools such as webpack, Rollup, or Vite to bundle your application, it is common
to configure your build tools to import CSS files using the import statement, just like importing
\f Styling Svelte components in six different ways 23","any JS files (some tools, such as Vite, even have been configured to allow importing CSS files such as
any JS files by default!):"," import './style.css';","Importing CSS Modules","In Vite, when you name your CSS files ending with .module.css, the CSS file is considered a
CSS Modules file. A CSS Module is a CSS file where all the class names defined within the file are
locally scoped:"," /* filename: style.module.css */
.highlight {
  background-color: yellow;
}","This means that the CSS class names specified within a CSS Module will not conflict with any class
names specified elsewhere, even with class names that have the same name.
This is because the build tool will transform the class names within CSS Modules to something unique
that is unlikely to have conflicts with any other names.
The following is an example of how the CSS rules in the preceding CSS Modules would turn out after
the build:"," /* the class name 'highlight' transformed into 'q3tu41d' */"," .q3tu41d {","   background-color: yellow;","When importing a CSS Module from a JavaScript module, the CSS Module exports an object, containing
the mapping of the original class name to the transformed class name:"," import styles from './style.module.css';"," styles.highlight; // 'q3tu41d'","In the preceding snippet, the imported styles module is an object, and we can get the transformed
class name, 'q3tu41d', through styles.highlight.
This allows you to use the transformed class name in your Svelte component:","

\f24 Implementing Styling and Theming"," We’ve seen six different ways of styling a Svelte component, but how do you choose when to use
which one?"," Choosing which method to style Svelte components"," Each method that we’ve seen so far has its pros and cons. Most of the time, choosing which method"," to style your Svelte component is up to personal preference and convenience."," Here are some of my personal preferences when choosing the method to style my Svelte component:"," • "," In the preceding example, we define the CSS custom property at the root element of the component,
the
element. As a CSS custom property value inherits from a parent, the child elements and
elements within the child components inherit the value from the
element.
As we are defining the CSS custom property at the
element of the component, elements that
are not the descendant of the
element will not be able to access the value.
If, instead, you would like to define the variable for all elements, even elements that are not the
descendant of the root element of our root component, you can define the CSS custom property at
the root of the document using the :root selector:"," "," You do not need to use the :global() pseudo-selector for :root, as it will always refer to the root
of the document, and never be scoped to the component.
\f Theming Svelte components with CSS custom properties 29","The :global() pseudo-selector is used in CSS Modules to define styles that apply globally, outside
the local module scope. In Svelte, when used within a component’s ","The great thing about using the CSS custom property is that we could dynamically change the value
of the CSS custom property, and the element’s style referencing the CSS custom property will be
updated automatically.
For example, I can specify the value of --text-color of
to be #222 or #eee, based on
a condition:","

  
","When the condition is true, the value of var(--text-color) is #222, and the value changes
to #eee when the condition changes to false.
\f30 Implementing Styling and Theming"," As you can see, CSS custom properties make it much easier to synchronize the style of elements.
Now, let’s look at a real-world example of using CSS custom properties: creating a dark/light theme mode."," Example – implementing a dark/light theme mode"," Dark mode is a color scheme where you have light-colored text on a dark-colored background. The"," idea behind dark mode is that it reduces the light coming from the screen while maintaining color"," contrast ratios so that the content is still readable. Less light coming from the device makes it more"," comfortable to read, especially in a low-light environment."," Most operating systems allow users to set their preference on whether to use a dark or light theme,"," and major browsers support a media query, prefers-color-scheme, to indicate a user’s"," system preference:"," @media (prefers-color-scheme: dark) {","   /* Dark theme styles go here */"," @media (prefers-color-scheme: light) {","   /* Light theme styles go here */"," Before we start, let’s decide on the variables needed."," To simplify things, we only change the background color and text color, so that would be --background-"," color and --text-color."," It is possible that your application has other colors, such as accent colors, shadow colors, and border"," colors, which would need to have different colors for dark and light themes."," Since these colors are going to be applied everywhere, we are going to define that on the root element"," with the :root pseudo-class:"," ","Now, in our Svelte components, we will need to start setting the color of the text to use var(--
text-color):"," ","And that’s it; the color of the text will be white when the system preference is on the dark theme, and
black when it is on the light theme.
With the inheriting nature of CSS custom properties, the value of the CSS custom property will be
determined by the closest parent element that has set the value.
This opens the door to allowing component users to specify the style of a component without having
to override style declarations through CSS rules of higher specificity.","Allowing users to change the styles of a component","Let’s say you style your component with CSS in the ","If you want to modify the color of the p element from outside of the component, you’ll need to know
the following:"," • The CSS selector that has a higher specificity to override the styles:
Here, we attempt to use the div :global(p) selector to override the color; however, without
knowing the implementation detail of the component, we do not know for sure whether our
selector has a higher specificity:

  

"," • The element structure of the component:"," To know which element’s color to override, we would have to know the element structure of"," the component and whether the element containing the text whose color we would like to"," change is a paragraph element."," The CSS rules and element structure of a component should not be part of the component’s public"," API. Overriding the style of a component via a higher specificity CSS rule is not recommended."," Small tweaks on the CSS rules or element structure will most likely break our CSS rule overrides."," A better approach is to expose a list of CSS custom properties that can be used to override the"," styles of the component:","

Hello World

"," "," The var() function accepts an optional second parameter, which is the fallback value if the
variable name in the first parameter does not exist.
If you use the component without defining --text-color, then the color of the paragraph
will fall back to red.
The color of the paragraph in the following code snippet is red:

  
"," However, if --text-color is set, then the value of --text-color is used instead:","
","   ","
"," In the preceding code snippet, the color of the paragraph is blue instead of red.
Setting CSS custom properties outside of a component is so common that Svelte provides a
shorthand to pass CSS custom properties into a component directly, without needing to create
a div element to wrap the component yourself:

\f Theming Svelte components with CSS custom properties 33"," This is equivalent to the following:","
","   ","
"," Here, \"display:contents\" is to make sure that the extra div does not participate in the
layout of the contents of .
If we are specifying a fallback value whenever we are using the CSS custom properties, we may find
ourselves repeating the fallback value a few more times. It would be a hassle if we are going to change
the fallback value. Let’s see how we can align the fallback value.","Aligning the fallback value","If we are using var(--text-color, red) across elements, you may quickly realize that we","should also define a CSS custom property for the fallback value, lest we will be repeating the value","multiple times, and it will potentially be troublesome to find and replace all of them in the future.","To define another CSS custom property, you will have to define it at the root element of your component.","If the value is local to your component and its descendent components only, then you should not","define the CSS custom property at the document root element via :root:","

Hello World


","This approach, however, requires us to use var(--fallback-color) wherever we are using var(-
-text-color).
A slightly better approach is to define a new CSS custom property that will have the value of --text-
color if defined, or red as a fallback:"," ","This way, the value of var(--internal-text-color) will always be defined, and it is more
convenient to use just one CSS custom property for elements thereafter.
\f34 Implementing Styling and Theming"," Summary
In this chapter, we went through six different methods to style a Svelte component. So, do you know
which method you are going to use to style your Svelte component? You should now know to choose
the approach that is best suited for the scenario.
We then saw how to use Tailwind CSS in a Svelte project. It takes some initial setup to get Tailwind up
and running at the beginning, but CSS frameworks such as Tailwind CSS usually come with predefined
CSS classes, and most of the time, you use a class attribute or the class: directive to apply them.
Finally, we covered how we can use the CSS custom property to theme Svelte components and how
to allow component users to customize the style of a component. You can now create and share Svelte
components while allowing others to have different styling than the default styles that you’ve created.
In the next chapter, we will look at how to manage the props and states of a Svelte component.
\f 3
Managing Props and State
In the world of web development, managing data effectively is crucial. Whether it’s the information
that flows between components or the internal state of a component, proper data management is the
backbone of a functional and responsive web application.
In this chapter, we will delve into the core concepts of managing props and state within a Svelte application.
First, we’ll clarify what props and states in Svelte are, laying the groundwork for understanding more
advanced topics. We then explore the concept of bindings, a feature in Svelte for keeping state and
element values or component props in sync.
We’ll then explore data flow within components, highlighting the differences between one-way data
flow and two-way data flow and why they matter. Moving on, we’ll discuss how to derive state from
props using Svelte’s reactive declarations. To conclude, we’ll offer tips for managing complex derived
states and explain how to update props based on those derived states.
By the end of the chapter, you’ll have a solid understanding of how to manage data within a Svelte
component, being equipped with practical tips and strategies to tackle common challenges effectively.
In this chapter, you will learn the following:"," • Defining props and state"," • Understanding bindings"," • One-way versus two-way data flow"," • Deriving states from props with a reactive declaration"," • Managing complex derived states"," • Updating props using derived states","Before we start to talk about props and state, let’s first define what props and state are in Svelte.
\f36 Managing Props and State"," Technical requirements
You can find all the code samples used in this chapter on GitHub at https://github.com/
PacktPublishing/Real-World-Svelte/tree/main/Chapter03"," Defining props and state"," In Svelte, both props and state are used to manage data within components. Props are a way to pass"," data from a parent component to a child component. This makes the child component flexible and"," reusable, as it can get different data from the parent as needed."," On the other hand, state is data that is initialized and managed internally within a component, unlike"," props, which are received from an external source. State allows a component to be self-contained"," and modular."," Defining props
Let’s start with props. Props in Svelte are defined using the export keyword. When you export a
variable in a Svelte component, it becomes a prop that you can pass data to from a parent component.
Here is a simple example:"," "," ","

{message}

"," In the preceding code snippet, we defined a Svelte component in a file named Child.svelte. In
the Svelte component, message is a prop. You can pass data to message from a parent component
like so:"," ","   import Child from './Child.svelte';"," "," In the preceding code snippet, we define another Svelte component in a file named Parent.
svelte. In the component, we import and use the Child component from Child.svelte. As
the Parent component includes the Child component, the Parent component is considered the
parent component of the imported Child component.
\f Defining props and state 37","In the parent component, you can set the message props of the child component to the value
\"Hello, World!\" by passing \"Hello, World!\" through the message attribute of the
component, as shown in the preceding code snippet.
In summary, props are defined using the export keyword, and their values are passed from the
parent component to the child component.","Defining state
Next, let’s look at the state. State is any data that is used and managed within a component. It is not
passed in from a parent component like props. Instead, it is defined within the component itself.
Here’s an example that illustrates state:"," ","
","Bindings are created through the bind: directive. In the preceding code snippet, the input element’s
value is bound to the name variable. When you type in the input, the name variable will update
automatically. Conversely, when you change the value of the name variable, the input element’s value
will also automatically update.
As demonstrated, bindings create a two-way data flow, enabling data changes to propagate from the
element to the component state, and from the component state into the element.
The previous example demonstrates binding on elements, but bindings can also work on components.
You can use the bind: directive to link the props of a component with your component’s state, as
shown in the following code:","

\f40 Managing Props and State"," In the preceding code snippet, we bind the username props of the component to the
name state variable. When you update the name state variable, the value of the username prop
will automatically reflect the new value; conversely, if you update the value of the username prop
from within the component, the value of the name state variable will automatically
update to match.
To further demonstrate this behavior, let’s make a slight modification to the code. Here’s the updated
version of the component:","

Name from App: {name}



"," In this code snippet, we’ve added a

element and a "," In the preceding code, we passed in extra attributes from the props into the button element along
with forwarding two events, click and dblclick, from the button element out to the component.
\f Reusing DOM event logic with custom events 77","The point I am trying to make here is that if you wish to reuse event listener logic via components, you
will find yourself having to take care of other attributes that go along with the element in the component.
We can do much more with a component, but if we are trying to reuse just the long-press behavior, then
reusing it by defining it in a component is a bit overkill, and it can grow unmanageable rather quickly.
So, what other options do we have?","Encapsulating logic into an action","A better option is to use an action to encapsulate the long-press behavior.","Let’s just do that and then I’ll explain why using an action is a better approach:"," function longPress(node) {
  let timer;
  function handleMousedown() {
    timer = setTimeout(() => {
      console.log('long press!');
    }, 2000);
  }
  function handleMouseup() {
    clearTimeout(timer);
  }
  node.addEventListener('mousedown', handleMousedown);
  node.addEventListener('mouseup', handleMouseup);
  return {
    destroy() {
     node.removeEventListener('mousedown', handleMousedown);
     node.removeEventListener('mouseup', handleMouseup);
    }
  }
}","With the action defined (as shown in the preceding code), we can use the action over multiple elements:"," "," ","You can apply the action to a different type of element:"," Hold on to me","You can also use it alongside other attributes or event listeners:","