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

Creating Reusable Components

Scorri per mostrare il menu

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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 5

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 2. Capitolo 5
some-alt