Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

svelte

How to use props in Svelte

Yasir Latif

Overview

In reactive component-based web applications, it is needed to pass data from one component to its children. Props is one of the ways to do component communication in Svelte. They're one-way, top-down approaches to communication as the parent component communicates to the child components. Props uses the export and import keywords to parse and receive data. The illustration given below shows how data is communicated from parent to child.

Props for component communication

Initially, the variables, user_id and user_name, are defined with some default values in index.svelte in a script. These variables are updated by the app.svelte file and are communicated as props. When these variables are passed in the HTML tag, the output value of the variables is updated as defined in props. The code to achieve the functionality is given in the following files:

The index.svelte file

<script>
  export let user_id = 'ID';
  export let user_name = 'no-name';
</script>
<div>
  <h2> Props implementation </h2>
  <span>{user_id}</span>
  <h3>{user_name}</h3>
</div>

The App.svelte file

<script>
  import Card from './index.svelte';
</script>
<Card user_id="12345" user_name="educative"/>

Example

<script>
  export let user_id = 'ID';
  export let user_name = 'no-name';
</script>
<div>
  <h2> Props implementation </h2>
  <span>{user_id}</span>
  <h3>{user_name}</h3>
</div>

Explanation

In App.svelte:

  • Line 4: We define values for the variables and pass them as props to the child.

In index.svelte:

  • Lines 7–8: We print the values of variables using tags that were defined using props in App.svelte.

RELATED TAGS

svelte

CONTRIBUTOR

Yasir Latif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring