In this article, we will look at how to pass data from parent to child components in Svelte.
In Svelte, we can pass data from parent to child components using props
. Props are properties that allow the parent to pass data to its child components.
Components receive props as parameters, which are data passed from the parent component. Consider the below example:
ParentComponent.svelte:
<script>
let message = "Message from Parent!";
</script>
<ChildComponent msg={message} />
ChildComponent.svelte:
<script>
export let msg;
</script>
<p>{msg}</p>
In this example, msg
property is passed from the ParentComponent
to the ChildComponent
.
To receive the msg
property, we need to declare prop in the child component.
export let msg;
We will look at another example in detail to understand this concept better.
Let’s create a basic project structure using the Svelte + Vite template.
Run the below command to create the project folder.
npm create vite@latest props-svelte-project -- --template svelte
This will create a folder props-svelte-project
in your current working directory. Feel free to change it to any name you want for your svelte project.
Next, navigate to the project folder and install all the packages required for the Svelte project by running the following command.
npm install
Once, the packages are installed, start the development server.
npm run dev
This will run our server on port 5173 by default. Open your web browser and visit http://localhost:5173/
We will create two components ParentComponent
and ChildComponent
. The parent component will contain the data which will be passed to the child component. For this example, we will take a list of animals to pass.
ParentComponent.svelte:
<script>
import ChildComponent from "./ChildComponent.svelte";
let animals = [
{ id: 1, type: "Dog", habitat: "Domestic", sound: "Bark" },
{ id: 2, type: "Cat", habitat: "Domestic", sound: "Meow" },
{ id: 3, type: "Frog", habitat: "Pond", sound: "Ribbit" },
];
</script>
<ChildComponent {animals} />
In this example, we declare animals
data and pass it to the childComponent
as a parameter.
ChildComponent.svelte:
<script>
export let animals;
</script>
<div>
<h2>Animal List</h2>
<table>
<thead>
<tr>
<th>Type</th>
<th>Habitat</th>
<th>Sound</th>
</tr>
</thead>
<tbody>
{#each animals as animal (animal.id)}
<tr>
<td>{animal.type}</td>
<td>{animal.habitat}</td>
<td>{animal.sound}</td>
</tr>
{/each}
</tbody>
</table>
</div>
In the childComponent
we declare animals
prop which will contain the data sent from the parent component.
The animals data is looped and displayed in table.
{#each animals as animal (animal.id)}
The App
component will call the parentComponent
as follows:
App.svelte
<script>
import ParentComponent from "./ParentComponent.svelte";
</script>
<ParentComponent />
That’s it! 🙂