0
0
Svelteframework~5 mins

Component composition in Svelte

Choose your learning style9 modes available
Introduction

Component composition helps you build bigger parts of your app by combining smaller, simple pieces. It keeps your code clean and easy to manage.

When you want to reuse a button style across different pages.
When you need to build a page layout using header, footer, and content parts.
When you want to split a complex form into smaller sections.
When you want to organize your app into logical blocks for easier updates.
Syntax
Svelte
<script>
  import ChildComponent from './ChildComponent.svelte';
</script>

<ChildComponent />
Use import to bring in another component file.
Use the imported component as a tag like <ChildComponent /> inside your main component.
Examples
This example shows how to compose a page with a header and footer components.
Svelte
<script>
  import Header from './Header.svelte';
  import Footer from './Footer.svelte';
</script>

<Header />
<main>
  <p>Page content here</p>
</main>
<Footer />
Here, a reusable Button component is used with a property to change its label.
Svelte
<script>
  import Button from './Button.svelte';
</script>

<Button text="Click me" />
Sample Program

This example shows a Button component that takes a text property. The main App component uses two Buttons with different labels. This demonstrates how small components can be combined and customized.

Svelte
<!-- Button.svelte -->
<script>
  export let text = "Button";
</script>
<button>{text}</button>

<!-- App.svelte -->
<script>
  import Button from './Button.svelte';
</script>

<h1>Welcome!</h1>
<Button text="Say Hello" />
<Button text="Say Goodbye" />
OutputSuccess
Important Notes

Each component should be in its own file for clarity.

Props (like text) let you customize components when composing.

Component composition makes your app easier to read and maintain.

Summary

Component composition means building UI by combining smaller components.

Use import and component tags to compose.

This helps reuse code and keep your app organized.