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

Passing Data with Props

Scorri per mostrare il menu

Modern frontend applications are usually built from many reusable components. Instead of hardcoding content directly inside each component, developers often pass data from one component to another.

In Svelte, this is done using props.

What Are Props?

Note
Definition

Props are values passed into a component from its parent component. They allow components to become flexible and reusable.

For example, a product card component could receive a title, price, image, or description. Instead of creating separate components for every product, the same component can display different data using props.

Creating a Component

Inside the src folder, create a new file called ProfileCard.svelte.

Add the following code:

<script>
  export let name;
  export let role;
</script>

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

<style>
  .card {
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 10px;
  }
</style>

The export let syntax creates props that can receive values from another component.

Passing Data into the Component

Now open App.svelte and import the component:

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

<ProfileCard
  name="Alex Johnson"
  role="Frontend Developer"
/>

The values passed into the component become available through the props.

Reusable Components

One of the biggest advantages of props is reusability.

You can create multiple cards using the same component while displaying different content.

<ProfileCard
  name="Emma Wilson"
  role="UI Designer"
/>

<ProfileCard
  name="Michael Brown"
  role="Backend Developer"
/>

This approach helps developers build scalable frontend applications more efficiently.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2

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 2
some-alt