How to use `slot` in svelte storybook

Viewed 2466

How can I add a svelte storybook story for the following component with the slot.

Button.svelte
<button>
 <slot />
</button>

Which I can use as

<script>
  import Button from './Button.svelte';
</script>

<Button>Hello World</Button>

How can I create a story for such components which has slots in it?

2 Answers

According to this example file in the official story book repo.

If we need to test components in a Svelte environment, for instance to test slot behaviour, then wrapping the component up in a view made just for the story is the simplest way to achieve this.

So for the time being it is probably most easy to follow this advice.

Stack.svelte

  <div class="flex-col">
      <slot><!-- optional fallback --></slot>
  </div>

StackView.svelte

<script lang="ts">
  import Stack from './Stack.svelte'

</script>

<Stack>
  <p>Slot 1</p>
  <p>Slot 2</p>
  <p>Slot 3</p>
</Stack>

stack.stories.js

import Stack from './StackView.svelte';

export default {
  title: 'Stack',
  component: Stack,
};


const Template = ({ ...args }) => ({
  Component: Stack,
  props: args,

});

export const Regular = Template.bind({});

That said, soon it may be possible to use svelte template syntax to write stories. I think that would solve the problem more elegant.

I used npx sb init command in order to add storybook to my svelte component lib. Below story definiton works for my SuccessLabel component:

<!--SuccessLabel.svelte-->
<div>
 <slot />
</div>

<style>
 div {
    position: relative;
    color: white;
    background-color: #28a745;
    border-color: #28a745;
    margin-top: -3px;
    padding: 10px;
    border-radius: 5px;
    border-top-right-radius: 0px;
    border-top-left-radius: 0px;
    font-size: 12px;
  }
</style>


<!--SuccessLabel.stories.svelte-->
<script>
 import { Meta, Story } from "@storybook/addon-svelte-csf";
 import SuccessLabel from "../src/components/labels/SuccessLabel.svelte";
</script>

<Meta title="Labels/SuccessLabel" component={SuccessLabel} />

<Story name="Default">
 <SuccessLabel>This message should be shown</SuccessLabel>
</Story>
Related