Intro to Props in Svelte.js

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 parent components to the child components.

Registering props

In svelte we need to use export keyword to register the props.

Button.svelte
<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.

App.svelte
<script>
  import Button from "./Button.svelte";</script>

<div>
  <h1>My first article</h1>
  <Button name="share" />  <Button name="like" />  <Button name="comment" /></div>

svelte-props-example1

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.

Button.svelte
<script>
  export let name;
  export let handleClick;</script>

<button on:click={handleClick}>{name}</button>

Now we are passing the function to the handleClick prop.

App.svelte
<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.

passing-functions-props