Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Default Prop Values | Components and Props
Introduction to Svelte

Default Prop Values

Swipe um das Menü anzuzeigen

Sometimes components may not receive every prop value from their parent component. In these situations, default prop values help prevent missing or empty content inside the interface.

Svelte allows you to assign default values directly when declaring props.

Why Default Values Matter

Imagine a profile card component that expects a user role. If the parent component forgets to pass the role prop, the interface could display empty content.

Default values provide fallback data when a prop is missing.

This helps components behave more predictably and improves the overall user experience.

Adding Default Prop Values

Open the ProfileCard.svelte component and update the props:

<script>
  export let name = "Unknown User";
  export let role = "Frontend Developer";
</script>

<div class="card">
  <h2>{name}</h2>
  <p>{role}</p>
</div>

Now the component automatically uses the default values if no props are provided.

Using the Component

Inside App.svelte, try rendering the component without passing all prop values:

<ProfileCard name="Alex Johnson" />

Because the role prop was not provided, Svelte uses the default value automatically.

Making Components More Flexible

Default values make reusable components safer and easier to work with. They reduce errors and allow components to display meaningful fallback content when data is incomplete.

This pattern is very common in modern frontend development.

question mark

What happens when a prop is not passed into a Svelte component that has a default value?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 2. Kapitel 3
some-alt