I have a question regarding reactive variable sharing between components. I have an example with checkboxes. Whenever only the sink checkbox is checked, I want to return a paragraph with a specific message. However, only the else statement is evaluated in component 2.
Maybe I have to use the store in svelte? I am not sure how to accomplish that.
A REPL can be found here: https://svelte.dev/repl/f2da2e91083f41098bd9b7c84ec199d2?version=3.49.0
The app component looks like this
<script>
import Component2 from './Component2.svelte';
let checked_sink = true;
let checked_source = false;
export let sink_source_checkbox = ["Sink"]
</script>
<label>
<input type=checkbox name="sink_source" value="Sink" bind:group={sink_source_checkbox} bind:checked={checked_sink}>
Sink
</label>
<label>
<input type=checkbox name="sink_source" value="Source" bind:group={sink_source_checkbox} bind:checked={checked_source}>
Source
</label>
<Component2/>
checked 1: {checked_sink} <br/>
checked 2: {checked_source} <br/>
{JSON.stringify(sink_source_checkbox.toString())}
And the 2nd component looks lik this
<script>
import sink_source_checkbox from './App.svelte';
</script>
{#if sink_source_checkbox.toString() === "Sink"}
<p>
It is only Sink
</p>
{:else}
<p>
It is not only Sink
</p>
{/if}
>Solution :
Instead of the import
export the variable from Component2
and pass it as a prop REPL
(There are probably various ways check for only ‘Sink’… And maybe you might reduce your example and just use the group binding without the parallel tracking of bind:checked
. I changed that in the Repl…)
<script>
export let checked
</script>
{#if checked.join() === "Sink"}
<p>
It is only Sink
</p>
{:else}
<p>
It is not only Sink
</p>
{/if}
In App.svelte
<Component2 checked={sink_source_checkbox}/>