How to use slots in Svelte

Overview

In component communication, it is possible that data passing from parent to child components is meant to render for the specific child and not for all. In such a scenario, data is passed using slots to render it as an HTML tag to a specific child. The slot is used as a tag in the child component while defining data for variables. The illustration below represents how data with HTML tags is rendered from a parent to a specific child.

Slots for component communication

The variables, user_id and user_name, that are defined with some default values in child1.svelte and child2.svelte are updated in the app.svelte file for a specific child—child1 using the slot keyword. The updated values are communicated to the child1 component that uses a slot as a tag to render a complete HTML tag defined with updated data inside it. The child2 remains unchanged. The code to achieve the functionality is given in the following files.

The child1.svelte file:

<script>
export let user_id = 'ID';
export let user_name = 'no-name';
</script>
<div class="card">
<h2>child using slots as component communication </h2>
<slot name="user_id">no id</slot>
<slot name="user_name">no name</slot>
</div>

The child2.svelte file:

<script>
export let user_id = 'ID';
export let user_name = 'no-name';
</script>
<div class="card">
<h2>child without using slots</h2>
<h3 name="user_id">no id</h3>
<h3 name="user_name">no name</h3>
</div>

The App.svelte file:

<script>
import Card from './child1.svelte';
import Card1 from './child2.svelte';
</script>
<Card>
<h4 slot="user_id">123456</h4>
<h4 slot="user_name">educative_slots</h4>
</Card>
<Card1>
<!-- no changes -->
</Card1>

Example

<script>
  export let user_id = 'ID';
  export let user_name = 'no-name';
</script>
<div class="card1">
  <h3>child without using slots</h3>
  <h4 name="user_id">no id</h4>
  <h4 name="user_name">no name</h4>
</div>

Explanation

In App.svelte:

  • Line 2: We import the child1 component.
  • Line 3: We import the child2 component.
  • Lines 6–7: The variables, user_id and user_name, are defined with a slot keyword with certain HTML tags for child1.
  • Line 10: We print the imported child2 without any changes.

In child1.svelte:

  • Lines 7–8: We render and display the updated data including defined HTML tags using the slot tags.

Copyright ©2024 Educative, Inc. All rights reserved