Readonly props in Svelte
📖 Scenario: You are building a simple user profile card in Svelte. The card shows a user's name and age. The user's name should not be changed inside the profile card component once it is set from outside.
🎯 Goal: Create a Svelte component that receives a name as a readonly prop and an age as a normal prop. Display both on the card. Ensure the name cannot be changed inside the component.
📋 What You'll Learn
Create a Svelte component named
UserProfile.svelte.Declare a prop
name that is readonly inside the component.Declare a prop
age that can be changed inside the component.Display the
name and age in the component's HTML.Try to change
name inside the component and ensure it causes an error or is prevented.Change
age inside the component and show the updated value.💡 Why This Matters
🌍 Real World
Readonly props are useful when you want to protect data passed from a parent component so it cannot be accidentally changed inside a child component.
💼 Career
Understanding how to manage props and their mutability is important for building reliable and maintainable UI components in Svelte.
Progress0 / 4 steps