I've created a simple component in Svelte 4, to display a standard checkbox and label. This I've hooked into an instance of Storybook 8 with a decorator - this is the code I'm using at present:
Checkbox.svelte
:
<script> import { createEventDispatcher } from 'svelte'; export let checked = false; export let label = ''; const dispatch = createEventDispatcher() function handleChange(event,) { const { checked } = event.target; dispatch('change', { checked }); } $: checked != checked;</script><label><input type="checkbox" bind:checked={checked} on:change={handleChange}> {label}</label><style> label { user-select: none; }</style>
CheckboxDecorator.svelte
:
<div><slot /></div><div id="message">Checkbox is unchecked</div><style> div { margin-top: 10px; }</style>
My issue is this: I want to display the Checkbox component in Storybook 8, and be able to retrieve and display the current checked/unchecked state of the checkbox outside of the component.
So far, my Checkbox.stories.js
file looks like this:
import Checkbox from "./Checkbox.svelte";import CheckboxDecorator from "./CheckboxDecorator.svelte";export default { title: "Example/Checkbox", component: Checkbox, decorators: [() => CheckboxDecorator], argTypes: { checked: { control: "boolean" }, label: { control: "text" }, onChange: { action: "changed" }, },};export const Primary = () => ({ Component: Checkbox, props: { label: "This is a test", }, on: { change: (event) => { const message = event.detail ? "Checkbox is checked" : "Checkbox is unchecked"; document.getElementById("message").innerHTML = message; }, },});
This renders the checkbox component OK - I'm using a decorator to add a dummy bit of markup with an id
of message
. The idea is so that when I click the checkbox, it updates the text to show checked or unchecked. At the moment, it's doing this, but only once - the text is updated from "Checkbox is unchecked" to "Checkbox is checked":
If I click on the checkbox again, it doesn't change - can anyone please help me to figure out what I've missed / done wrong?
I've checked through SO and played with a few variations: I am reasonably confident that the component itself is OK based on other examples. Changing the click handler to pipe out the results of checked
via the console shows that it flips correctly between state.