Intro to Props in Svelte.js
In this tutorial, we are going to learn about how to use props in svelte with the help of examples.
Props
Props help us to pass the data from the parent component to the child components and props and immutable in svelte.
Registering props
In svelte, we can use the export
keyword to register the props.
Here is an example:
<script>
//name prop is registered
export let name;</script>
<button>{name}</button>
In the above code, we have registered a name
prop inside the Button
component and added it to our button
element.
Passing Data to props
Let’s pass the data to that prop by using the registered prop
name.
<script>
import Button from "./Button.svelte";</script>
<div>
<h1>My first article</h1>
<Button name="share" /> <Button name="like" /> <Button name="comment" /></div>
Passing functions to props
Let’s register a new prop called handleClick
which helps us to pass the event handler function as a prop from the parent component.
<script>
export let name;
export let handleClick;</script>
<button on:click={handleClick}>{name}</button>
Now we are passing the function to the handleClick
prop.
<script>
import Button from "./Button.svelte";
function Share() {
console.log("share button worked");
}
function Like() {
console.log("like button worked");
}
function Comment() {
console.log("comment button worked");
}
</script>
<div>
<h1>My first article</h1>
<Button name="share" handleClick={Share} /> <Button name="like" handleClick={Like} /> <Button name="comment" handleClick={Comment} /></div>
In the above code, we have created three functions and passed it to the handleClick
prop.