Transcript from the "Props" Lesson
[00:00:00]
>> We can also assign directly to properties of arrays and objects the same way that we assign to free variables. So another way that we could do this is numbers[numbers.length] = numbers.length + 1. And that works exactly how you would expect. At some point, when you're building an application, you're gonna need to parse data from one component to another.
[00:00:25] And for that, we use something called a prop. A prop is basically an attribute on an element, and it stands for properties. So here we have some state inside the nested component answer, and we're showing it inside this paragraph tag, and it's coming across as undefined. Even though we're parsing it through from here, nested answer = 42.
[00:00:53] And the reason for that is that as far as the nested component is concerned, this is private state that nothing else gets to interfere with. What we need to do is tell svelte the answer should be considered a property that can be set by a parent component. And the way that we do that is again by abusing some existing JavaScript syntax, we're gonna use the export keyword.
[00:01:16] This tells svelte that if the parent sets a value for this, we just parse it through. And obviously if we change that, it'll update in the manner that you would expect, so there's a little caveat now here. This might seem a little bit weird if you're used to using the export keyword in your JavaScript modules.
[00:01:36] Again, it has to be syntactically valid. And this is a really convenient way of using something that's in the language that we weren't otherwise gonna be using to fulfill a purpose that would otherwise be very difficult and awkward. So just kind of roll with it for now and it'll soon become second nature.
[00:01:57] So we can set a default value for answer, like so. And then if the parent component doesn't provide a value for that prop, then it'll fall back to the default. First answer is 42, the second answer is determined by the child. And finally, in the prop section, we have the concept of spread props.
[00:02:29] Sometimes you have a bundle of properties and you wanna parse them all through to component. In some situations, you might not know what is gonna be in that object. And you don't, like you physically unable to say A equals A, B equals B, C equals D, because you don't know whether it's gonna be A, B, C, D, E, or P, Q, R, S, T.
[00:02:47] So we use the spread syntax which looks like this. I'm just gonna get rid of all of these individual properties and parse them through like so, dot, dot, dot, pkg. And then it passes through the information exactly the same way that you would expect. And inside here, we're exporting all of the properties of that spread objects as individual props.
[00:03:13] So nothing needs to change inside the child component.