You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
45 Min
11 Seg
Curso de Svelte

Curso de Svelte

Oscar Barajas Tavares

Oscar Barajas Tavares

Props

7/26
Resources

How to create a component and manage properties in Svelte?

Property management in Svelte is essential for building robust and scalable applications. This article will discuss the creation of components and how to work with properties and defaults, as well as properties per propagation.

How to create a new component with default values?

Creating a component in Svelte starts by defining a file with the name of the component. To maintain conventions, it starts with a capital letter and uses the extension .svelte.

  1. Create the component: Starts the component with a script.
  2. Define the properties: Uses the export let method to manage the properties that will be received from other components.
  3. Set default values: For a default value, assign a value when using export let.
<script> export let anotherText = "Lorem ipsum"; </script> </script>
<div class="text"> <p>{anotherText}</p></div>

In this example, the component named Text receives an anotherText property, which defaults to "Lorem ipsum". This ensures that if no value is received from the parent component, a text will still be displayed.

How to integrate a component into the application?

Once the component is created, the next step is to integrate it into your main application.

  1. Import the component: Use the import statement to add it to your application.
  2. Use the component: Call the component and assign the properties you need.
<script> import Text from './components/Text.svelte'; </script>
<Text anotherText="Hello" />

Here, the Text component is imported and passed the anotherText property with the value "Hello".

How to work with objects and properties by propagation?

Svelte allows multiple properties to be passed through an object using the propagation technique. This method can simplify the handling of multiple properties.

  1. Create an object with data: In your main application, define an object that contains all the necessary data.
<script> const data = { name: "Óscar", lastName: "Barajas", age: 31 };</script>
  1. Import and use the component: Fetch the component and integrate the object using propagation.
<script> import Person from './components/Person.svelte'; </script>
<Person {...data} />

Using the {...} braces propagates all values from the data object to the Person component.

How to receive and handle properties in the receiving component?

With properties propagated into the receiving component, they must be set using export let, and then represented as needed within the component.

<script> export let name; export let lastName; export let age; </script> </script>
<div class="person"> <p>{name} {lastName}, {age}</p></div> </div>

By properly structuring the properties in the child component, you can break them down and use them efficiently and clearly.

Working with components and properties in Svelte is an essential skill for any developer who wants to create modern, efficient applications. Keep exploring and improving your Svelte skills to fully master this powerful framework.

Contributions 17

Questions 4

Sort by:

Want to see more contributions, questions and answers from the community?

🐪 camelCase
🧮 PascalCase
🐍 snake_case
🍢 kebab-case

Recomiendo la herramienta Relative path para apoyarse en el llamado de archivos.

Typo min 08:38 dage

Paso de argumentos por propagación: Se envían de forma destructurada los elementos.

{ ...Objeto }

También se puede mandar todo el objeto como un prop

<Person data={data} />

y después en nuestro componente desestructurarlo

export let data;
const {name, lastName, age} = data;

Es el mismo resultado pero para los que quieran seguir la notación del prop=“value” puede ser más útil

En lugar de que realices varias veces

export let name
export let lastName
export let age

Puedes optar por

export let name, lastName, age

Propiedades en Svelte

La podemos realizar mediante dos formas:

  1. De forma explícita:
// Componente padre App.svelte
<main>
...
<Text anotherText="Hello!" />
...
</main>
  1. De forma implícita:
// Componente padre App.svelte
<main>
...
<Person {...data} />
...html
</main>
// Componente hijo Person.svelte
<script>
  export let name;
  export let gitHub;
  export let rol;
</script>
<div class="p">{name} {gitHub} {rol}</div>

Nota. Considera que la segunda forma deberá estar llamado igualmente en el componente hijo.

Creamos la variable en la estructura de JS

export let anotherText;

Luego la utilizamos en la estructura html

<p>{anotherText}</p>

Luego en el componente que vamos a utilizar podemos enviarle el valor

<Text anotherText="Hola" />

Si por algún motivo no le vamos a enviar valor y queremos que tenga uno por default haremos lo siguiente:

export let anotherText = "Value for default";

Podemos usar la desestructuración de objetos:
Para pasar los props a Person como un solo dato: <Person data={data} />
Luego en el componente:
`<script>
export let data;

const {nombre, apellido, edad}=data;
</script>`

<div class="Person"> <p>{ nombre} { apellido } { edad }</p> </div>

Las props son una forma de comunicar nuestros componentes padres con nuestros hijos, mandandoles datos para que los hijos puedan pintarlo en pantalla o traer datos de una API, pero es importante saber que al pasar una prop a un componente hijo no podremos modificarlos.

Pueden asignar los valores en una sola linea ej.:

./components/Person.svelte

<script>
    export let name, last, age
</script>

<div class="person">
    <ul>
        <li>Name: {name}</li>
        <li>Last: {last}</li>
        <li>Age: {age}</li>
    </ul>
</div>```
Cuando queremos enviar como prop un objeto completo podemos usar {…objeto} siempre y cuando los campos del objeto coincidan con los nombres de las props del componente (ejemplo name o lastName)

Oscar necesita lentes xD

Me encanta lo pausado que habla el profesor, porque le capto todo

👌

Pasando un objeto por propagación.

<script>
  const data = {
    name: 'Cristian',
    lastName: 'Perez',
    age: 30
  };
</script>

Básicamente creando un destructuring igual en React.

 <Person {...data} />

Tienes que ver este codigo antes de empezar a ver el video.

<Person 
	name={data.name} 
	lastname={data.lastname} 
	age={data.age}>
</Person>