I have a component that maintains a selection as an array and a child component that determines its state by seeing if it is included in that array. When I change the array, the child component does not re-render. How do I fix this?
REPL: https://svelte.dev/repl/f2074ef75dee444faaee005b8b7cf9b9
App.svelte
<script>
import Nested from "./Nested.svelte";
let selection = [];
function isSelected(n) {
return selection.indexOf(n) > -1;
}
function click(e) {
const n = e.detail.number;
if (isSelected(n)) {
selection = selection.filter(x => x != n);
} else {
selection = [...selection, n];
}
console.log("Selection is", selection);
}
</script>
{#each [1, 2, 3] as number}
<Nested
{number}
selected={isSelected(number)}
on:click={click} />
{/each}
Nested.svelte
<script>
export let selected, number;
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
function click() {
dispatch("click", {
number
});
}
</script>
<style>
.selected {
color: red;
}
</style>
<div class:selected={selected} on:click={click}>
{number}
</div>