Author -  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 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:

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 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY