by Sai gowtham

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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course