let's say I want to have a custom attribute where I can get some information from the parent element.
in svelte is easy, the syntax is like this:
MyChild.svelte
<script>
export let x;
</script>
<div>choosed value: {x}</div>
MyParent.svelte
<main>
<MyChild x={10} />
</main>
but let's say I didn't want to always pass the attribute value
<MyChild x={10} />
<MyChild /> <!-- this time I don't want to pass the value -->
I want if I don't pass the value then it will use a secondary value.
in react we have ??
or ||
,
- but in svelte don't seem to work
- seems mandatory
Property 'x' is missing in type...
so svelte tell me the problem before compiling
- which is safe and good
- but in my case,
- I want to create 1 attribute that is mandatory,
- and other 5 optional (not important, in most case are repetitive so this is why are optional)
is there a workaround?
so I want something like
export let x ?? 0;
// get "x" if you find an attribute
// then set the variable "x" to "x"
// but if the user doesn't add the attribute uses the second value "??"
// same as if x is undefined/null
or like this
export let x ?? 4.1658126;
or like this
export let x ?? MY_CONSTANT_VAR;
CodePudding user response:
do like this:
<script>
export let x = 0;
</script>
<div>choosed value: {x}</div>
now it will work in the parent without that error in the IDE
<main>
<MyChild x={10} /> <!-- choosed value: 10 -->
<MyChild /> <!-- choosed value: 0 -->
</main>
There is no need for ??
, just use =