Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating Reusable Components | Components and Props
Introduction to Svelte

Creating Reusable Components

Stryg for at vise menuen

Reusable components are one of the most important ideas in modern frontend development. Instead of rebuilding the same interface multiple times, developers create flexible components that can be reused throughout an application.

This approach helps keep projects cleaner, faster to develop, and easier to maintain.

Why Reusable Components Matter

Imagine building an application with dozens of product cards, buttons, or profile sections. Creating separate HTML for every element would quickly become repetitive and difficult to manage.

Reusable components solve this problem by allowing developers to create a single component that can display different data using props.

This makes applications more scalable and organized.

Building a Reusable Button Component

Create a new file called Button.svelte inside the src folder.

Add the following code:

<script>
  export let text = "Click Me";
</script>

<button>{text}</button>

<style>
  button {
    padding: 10px 18px;
    border: none;
    border-radius: 8px;
    background-color: #7c3aed;
    color: white;
    cursor: pointer;
  }
</style>

This component can now be reused anywhere in the application.

Using the Component Multiple Times

Open App.svelte and import the component:

<script>
  import Button from './Button.svelte';
</script>

<Button text="Save" />
<Button text="Delete" />
<Button text="Continue" />

Even though all buttons use the same component, each one displays different content through props.

question mark

Why are reusable components important in modern frontend development?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 5

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 2. Kapitel 5
some-alt