I have some buttons and when i click on each of them the background-color should change. Right now it changes the color of all buttons when one is clicked. However it should be for each button individually. Does someone know how to do that in?
That's my main svelte class:
<script lang="ts">
import Button from './Button.svelte';
let empty = false;
function changeBtnState() {
if (empty) {
empty = false;
} else {
empty = true;
}
}
</script>
<Button label="process" {empty} onClickFn={changeBtnState} />
<Button label="date" {empty} onClickFn={changeBtnState} />
<style lang="scss">
.main-button.empty {
background-color: red;
}
</style>
And that's my button component
<script lang="ts">
export let label: string = 'test';
export let onClickFn: () => void = () => {
return;
};
export let empty = false;
</script>
<button
type="submit"
class="main-button"
class:empty={empty}
on:click={onClickFn}>{label}</button
>
<style lang="scss">
.main-button{
background-color: #f2eee2;
}
</style>
The problem is that you bind both your button's empty attribute to the same variable:
<Button label="process" {empty} onClickFn={changeBtnState} />
<Button label="date" {empty} onClickFn={changeBtnState} />
You need a separate one for each button.
What you can do it's to integrate the changeBtnState inside the Button component. So the empty variable is defined IN the component and is different for each of them. Another option if you don't want to integrate it in one component, is yo create an array of "empty" variables (1 per button).