0
0
Svelteframework~20 mins

Readonly props in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Setup props for user name and age
Create a Svelte component with two props: declare export let name and export let age.
Svelte
Need a hint?

Use export let to declare props in Svelte.

2
Make the name prop readonly
Add const before name to make it readonly: write export const name and keep export let age as is.
Svelte
Need a hint?

Use export const to make a prop readonly in Svelte.

3
Try to change name inside the component
Add a line inside the component that tries to assign name = 'New Name'. This should cause an error or be prevented because name is readonly.
Svelte
Need a hint?

Readonly props cannot be reassigned inside the component.

4
Change age inside the component and display updated value
Add a line that changes age to age + 1 inside the component. Display the updated age below the original age.
Svelte
Need a hint?

Normal props declared with export let can be changed inside the component.