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...