omar
omar

Reputation: 190

svelte prop value not working with if statement

this is my svelte component code

<script>
    export let canCascade = true;
    let show = true;

    function cascade() {
        if (canCascade) {
            show = !show;
        }
    }
</script>

{#if show}
<div class="shade" on:click|self={cascade}>
    shade
</div>
{/if}

When I use the component as <Component canCascade=false /> the 'if block' doesn't work. But hard-coding the value inside just works fine. Am I missing something here - some conceptual error?

Upvotes: 0

Views: 2274

Answers (2)

Idan Krupnik
Idan Krupnik

Reputation: 463

In Svelte when we want to pass JavaScript value / expression to an attribute of a component we need to wrap the value / expression with curly brackets {}.

Otherwise, it will be used as a string.

As an example, take a look at the following code:

Component.svelte:

<script>
  export let test = true;

  $test: console.log(`typeof test = ${typeof test}`);
</script>

App.svelte:

<script>
  import Component from "./Component.svelte";
</script>

<Component test=true />
<div />

When you will open the console inside the browser developer tools, the output will be:

typeof test = string

Upvotes: 1

cascading-jox
cascading-jox

Reputation: 1131

Like @Corrl pointed out in the comments, you need to use {brackets}. If you don't, the variable will follow the rules of an html attribute.

Working repl https://svelte.dev/repl/d13df678eab243e9a13fb705da197219?version=3

Upvotes: 1

Related Questions