An example of an optional prop would be very helpful in the tutorial. Remember that the tutorial is for people who are unfamiliar with the framework. While you could figure this out, it's often hidden.
e.g.
export let optional = undefined;
The trick here is to set the default value to undefined. This is useful for making re-usable components where you may want to pass in optional props for "id", "class" (reserved word so perhaps className?), "style", "delegate", etc...
Might be a stupid question but how do we get an optional prop with a default value?
Just give it a default value:
https://svelte.dev/repl/5a79ae977a084489b72f2ec595a53e07?version=3.12.1
Great idea! @rlaferla would you like to help writing the docs?
@rlaferla But in that case it's not optional anymore.. I'm missing something. I can't do both:
export let optional = undefined;export let optional = 42;I guess you could do:
export let optionalPropA = undefined;
const defaultPropA = 42;
const propA = optionalPropA !== undefined ? optionalPropA : defaultPropA;
But that looks boilerplaty.
@TimAstier
I think what @rlaferla meant is if you don't provide value for props that do not have default value will get a runtime warning for missing props.
One way to make props optional and without a default value is to use the
export let foo = undefined;
@tanhauhau Yes, I will contribute from time to time.
I'll convert this to a tutorial page later on this week maybe:
https://svelte.dev/repl/ed0fe4b6d2634eada2627a06a72fa9a6?version=3.12.1
It shows behavior of undefined for both a value attribute and boolean attribute.
Not sure if this is 100% the place to post this, but the Lifecycle/onMount tutorial page example code is missing "export", causing the value that should be 42 to be undefined instead.
https://svelte.dev/tutorial/onmount
Checking into the Svelte docs site over the last year or so I've found the examples more often don't work than do. This is severely detrimental to anyone curious about Svelte. Happy to help fix them if that's something I can do.
@jspinella The tutorials are intended to be completed by the user. They are broken to start with and work as you follow along. There is a "show me" button at the bottom that will complete the tutorial for you.
I'm confused by this issue. Optional and default prop values are bound together. If a value is optional it can't have a default but having a default value makes setting that prop optional. Maybe the tutorial just needs some rewording/ clarification.
@pngwn Ahhh that makes sense. I had thought the examples worked fine at one point but I was probably mixing up the "tutorials" with the "examples".
Most helpful comment
@TimAstier
I think what @rlaferla meant is if you don't provide value for props that do not have default value will get a runtime warning for missing props.
One way to make props optional and without a default value is to use the