Reputation: 1811
First of all, sorry if the question didnt make much sense. Finding it hard to frame the question properly but this is what I am trying to do.
Current Behaviour
Able to toggle the css class between the two h1 tags but unable to toggle after enabling toggle; meaning unable to remove css class on the h1
tag where css class is already enabled.
Intended Behaviour
On click of the same active h1
, it should remove the css class.
Link to the REPL, also the same code below.
App
<script>
import Component2 from './Component2.svelte'
let numbers = [1,2];
let selectedOption;
const runThis = (i) => {
selectedOption = i;
}
</script>
{#each numbers as number}
<Component2 isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}
Component.svelte
<script>
export let number;
export let isSelected;
</script>
<h1 on:click class:red={isSelected}>Hello {number}</h1>
<style>
.red{
color: red;
}
</style>
Upvotes: 1
Views: 459
Reputation: 14873
Issue by toggling is that you have to be sure that the new selected number isn't the one already selected. So if the current selectedOption
is the same as i
, just set it to null
:
const runThis = (i) => {
selectedOption = i !== selectedOption ? i : null;
}
See the REPL.
Upvotes: 1
Reputation: 1811
Found the answer
App.svelte
<script>
import Component from './Component.svelte'
let numbers = [1,2];
let selectedOption;
const runThis = (i) => {
if(selectedOption===i)
selectedOption=-1
else
selectedOption = i;
}
</script>
{#each numbers as number}
<Component isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}
Component.svelte
//same
Upvotes: 0