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.
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"/>
<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>
In App.svelte
:
In index.svelte
:
App.svelte
.Free Resources