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

Creating Reusable Components

Svep för att visa menyn

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änligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 5

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 5
some-alt