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

Deriving states from props with a reactive declaration

It’s common in Svelte to create new state variables based on the values of props.

For instance, a <DateLabel /> component might accept a date value as a prop and display a formatted date inside a <label> element. To use the <DateLabel> component, you might write the following:

<DateLabel date={new Date(2023,5,5)} />

To display the date as formatted text, you could first define a variable named label, deriving its value from the date prop:

<!-- filename: DateLabel.svelte -->
<script>
  export let date;
  // Deriving the 'label' variable from the 'date' prop
  let label = date.toLocaleDateString();
</script>
<label>{label}</label>

In this code snippet, we defined a variable called label and derived its value from the date prop using the toLocaleDateString() method. This variable is then used inside a <label...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Real-World Svelte
Published in: Dec 2023Publisher: PacktISBN-13: 9781804616031

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