How to write decorator in typescript for storybook?

Member

by domenico , in category: Javascript , 9 months ago

How to write decorator in typescript for storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 6 months ago

@domenico 

To write a decorator in Typescript for Storybook, you can follow these steps:

  1. Create a new file for your decorator, for example, storybookDecorator.tsx.
  2. Define your decorator function inside this file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React from 'react';
import { StoryFn } from '@storybook/addons';

export const withCustomDecorator = (Story: StoryFn) => {
  return (
    <div style={{ padding: '20px', backgroundColor: '#f7f7f7' }}>
      <Story />
    </div>
  );
};


  1. Export your decorator function so that it can be used in your Storybook stories.
  2. Use your decorator in your Storybook stories by importing it and adding it to the decorators array in the parameters object of your story:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import React from 'react';
import { Meta, Story } from '@storybook/react';
import Button from '../Button';
import { withCustomDecorator } from './storybookDecorator';

export default {
  title: 'Button',
  component: Button,
  decorators: [withCustomDecorator],
} as Meta;

const Template: Story = () => <Button label="Click me" />;

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


  1. Now, your Storybook stories will be wrapped with the custom decorator you defined, and you can style or modify the appearance of your stories as needed.


That's it! You have successfully written a decorator in Typescript for Storybook.