0
0
Svelteframework~5 mins

Readonly props in Svelte

Choose your learning style9 modes available
Introduction

Readonly props let a component receive data without changing it. This keeps data safe and predictable.

When you want to pass information to a child component that should not be changed there.
When you want to make sure a component only reads data but does not modify it.
When you want to avoid bugs caused by accidental changes to input data.
When you want to clearly show which data flows down and stays constant.
Syntax
Svelte
<script>
  export let name;
</script>

<!-- Use {name} in markup -->

Props are readonly by default in Svelte. You cannot assign a new value to a prop inside the child component.

Trying to change a prop inside the child will cause an error or warning.

Examples
This component receives a title prop and shows it. The prop is readonly.
Svelte
<script>
  export let title;
</script>

<h1>{title}</h1>
You cannot assign a new value to count inside the component because it is readonly.
Svelte
<script>
  export let count;

  // count = 5; // This would cause an error
</script>

<p>Count is {count}</p>
Sample Program

The parent sends a message prop to the child. The child shows it but cannot change it.

Svelte
<!-- Parent.svelte -->
<script>
  import Child from './Child.svelte';
  let message = 'Hello from parent';
</script>

<Child text={message} />

<!-- Child.svelte -->
<script>
  export let text;

  // text = 'Changed'; // This will cause an error
</script>

<p>{text}</p>
OutputSuccess
Important Notes

Props in Svelte are readonly by design to keep data flow clear and safe.

If you need to change data, do it in the parent and pass updated props down.

Use events to notify the parent if the child wants to request changes.

Summary

Props are readonly in Svelte components by default.

This prevents accidental changes inside child components.

Data flows down from parent to child clearly and safely.