Simply props

series on svelte part 5

ยท

2 min read

Simply props

Welcome back folks .So far we have deal with the variables and states available within component .In this tutorial we are going to discuss about Props .

Many time we need to pass data from one component down to its children. To do that, we need to declare properties, generally shortened to 'props'.

Parents --------- >>-------children

Props are defined in children using export keyword which defines that this is the variable / state which will be provided by its parent.

child.svelte ,

<script>
  export let name;
 //name is prop variable whose value will be provided by parent component
    </script>
<p>My name is {name}</p>

parent.svelte

<script>
    import Child from './child.svelte';
</script>

<Child name={"Sanju"}/>

Here we pass name as prop to Child component. In this way we can pass object , function ,array etc and can handle them in child .

If we does not send any props to a child component which is expecting some prop value then UNDEFINED will given to that prop variable. So to avoid such condition we can give default prop value to child component as

<script>
    export let name = "baanu",
</script>

When name prop is not send from parent then this default value will be used as prop value.

We can also use spread operator .If we send object as props , we can specify spread operator for shortening the syntax and better readability. Lets see an example.

<script>
    import Title from './title.svelte';

    const name = {
        firstName: 'Jay',
        lastName: 'Shankar',
        middleName: 'Prasad'
    };
</script>

<Title firstName={name.firstName} lastName={name.lastName} middleName={name.middleName} />
<script>
    import Title from './title.svelte';

    const name = {
        firstName: 'Jay',
        lastName: 'Shankar',
        middleName: 'Prasad'
    };
</script>

<Title {...name />

Now,in child component the prop's names should be same as object key's values

<script>
    export let fisrtName;
    export let middleName;
    export let lastName;
</script>

So ,this was small but important concept in Svelte .That's all for this tutorial .In the next part we will go through Binding and concepts related to it .

You can also read introduction, setup , loops and if-else , Events for better understanding .

Thanks for reading part 5! I hope it has been a helpful read. Please leave any questions or comments below. Don't forget to like and share the article if it helps you in any way. Stay curious, cheers.