Mr. Baudin
Mr. Baudin

Reputation: 2254

Conditional Rendering in Svelte

I am trying to conditionally render a field in a form based on a value in that form. I've created an example here:

https://svelte.dev/repl/54917929b89646339a9c7498c13f7b38?version=3.17.3

The gist of the question is that I'm creating a control and using its slot which contains some conditional logic.

Upvotes: 0

Views: 2304

Answers (1)

rixo
rixo

Reputation: 25041

Context is not reactive in Svelte, meaning changes in value are not tracked. You need something reactive, for the view to react.

What you can do is put a store in the context.

For example, in App.svelte:

    import { setContext } from 'svelte'
    import { writable } from 'svelte/store'
    let data = writable({});
    setContext("data", data);

Then, deeper in the child component (notice the $ prefix to read / write the store value in the template):

  let data = getContext("data");

  const handleInput = event => {

    // NOTE the dollar prefix to access the value
    $data[fieldName] =
      event.target.type === "checkbox"
        ? event.target.checked
        : event.target.value;
  };

REPL using store in context

Another way would be simply to use two way binding.

In App.svelte:

<script>
    // ...
    let data = {};
</script>

<Form submit={submit}>
    <FormField bind:data ... />
    {#if data.type && data.type === 'Local'}
        <FormField bind:data ... />
    {/if}
</Form>

And in your FormField.svelte:

    export let data

REPL using binding

Upvotes: 1

Related Questions