create account

Storybook — How to Use Decorators? (+ React Examples) by simplestack

View this thread on: hive.blogpeakd.comecency.com
· @simplestack ·
Storybook — How to Use Decorators? (+ React Examples)
<center>
![image.png](https://files.peakd.com/file/peakd-hive/simplestack/23wMURk3rTDxvP1NkpurkV7cToQDuoyvic54yXNs21rKJhWHwrJNd8SgeAPig58ij9aC1.png)
</center>

Decorators are functions that add extra functionality around how a story is rendered. Addons often use decorators to enhance stories (e.g., by adding extra markup) or to collect information about the rendering process.

In your stories, you’ll commonly use decorators to wrap them with additional HTML or to simulate specific contexts.

# Wrap stories with extra markup

Certain components need to be placed within a specific container or “harness” to display correctly. For example, a component that stretches to the edge of its container might look better with some padding around it. You can use a decorator to add this necessary markup (like padding) to all stories of that component.

<center>
![image.png](https://files.peakd.com/file/peakd-hive/simplestack/23tcNzkqogwzkb9BiSNQMLw5go1qYLQzY1xrgTNX14SrXHy8i2RZvBfvLyDiKZypEVos7.png)
</center>

```
import type { Meta } from '@storybook/react';

import { YourComponent } from './YourComponent';

const meta: Meta<typeof YourComponent> = {
  component: YourComponent,
  decorators: [
    (Story) => (
      <div style={{ margin: '3em' }}>
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </div>
    ),
  ],
};

export default meta;
```

<center>
![image.png](https://files.peakd.com/file/peakd-hive/simplestack/23tSzCauiq84RezrxgHG1fuHfZb1QXWJvwkNiivTjpbY4aRQ2FQdeRUwqQLjJWA4rK8ua.png)
</center>

# “Context” for mocking

Decorator functions receive a “story context” object as their second argument. This object provides access to several useful properties:

- args: The arguments passed to the story. You can use these within the decorator, and some might not even be used directly by the story itself.
- argTypes: Allows you to customize and fine-tune the story's arguments.
- globals: Project-level global settings within Storybook. These can often be controlled interactively using Storybook's toolbar.
- hooks: Storybook's API hooks (like useArgs).
- parameters: Static metadata associated with the story, commonly used to configure Storybook features and addons.
- viewMode: Indicates the currently active Storybook view (e.g., "canvas" or "docs").

The story context lets you dynamically change how your decorator works based on the story’s settings. For instance, you could create a layout decorator that applies a specific layout (“page” or “page-mobile”) depending on the value of parameters.pageLayout.

```
import React from 'react';

import type { Preview } from '@storybook/react';

const preview: Preview = {
  decorators: [
    // 👇 Defining the decorator in the preview file applies it to all stories
    (Story, { parameters }) => {
      // 👇 Make it configurable by reading from parameters
      const { pageLayout } = parameters;
      switch (pageLayout) {
        case 'page':
          return (
            // Your page layout is probably a little more complex than this ;)
            <div className="page-layout">
              <Story />
            </div>
          );
        case 'page-mobile':
          return (
            <div className="page-mobile-layout">
              <Story />
            </div>
          );
        default:
          // In the default case, don't apply a layout
          return <Story />;
      }
    },
  ],
};

export default preview;
```

> The section on configuring a mock provider shows another example of how the story context can be used. It demonstrates how to dynamically change the theme applied to a component, similar to the layout example, based on settings within the story’s context.

If your components rely on data fetched from external sources (like an API) to render correctly, decorators can be used to provide mock data. This avoids the need to restructure your components just for Storybook. Several methods exist for mocking data with decorators, depending on your data-loading approach.

# Story decorators

To apply a decorator to a specific story only, use the decorators key within that story's definition (the named export).

```
import type { Meta, StoryObj } from '@storybook/react';

import { Button } from './Button';

const meta: Meta<typeof Button> = {
  component: Button,
};

export default meta;
type Story = StoryObj<typeof Button>;

export const Primary: Story = {
  decorators: [
    (Story) => (
      <div style={{ margin: '3em' }}>
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </div>
    ),
  ],
};
```

Keeping the core story focused solely on rendering the component itself, and using decorators for any extra HTML or supporting components, is a good practice. This separation makes the story cleaner and especially benefits features like the Source Doc Block, which then accurately reflects the component’s code.

# Component decorators

To apply a decorator to every story of a particular component, use the decorators key within the default export in your Component Story Format (CSF) file.

```
import type { Meta, StoryObj } from '@storybook/react';

import { Button } from './Button';

const meta: Meta<typeof Button> = {
  component: Button,
  decorators: [
    (Story) => (
      <div style={{ margin: '3em' }}>
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </div>
    ),
  ],
};

export default meta;
```

# Global decorators

You can also apply a decorator globally to all stories in your Storybook project. Do this by using the decorators property in the export default of your .storybook/preview.js or .storybook/preview.ts configuration file.

```
import React from 'react';

import { Preview } from '@storybook/react';

const preview: Preview = {
  decorators: [
    (Story) => (
      <div style={{ margin: '3em' }}>
        {/* 👇 Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
        <Story />
      </div>
    ),
  ],
};

export default preview;
```

# Decorator inheritance

Just like parameters, decorators can be defined at three levels: globally, for a component, and for a specific story. When a story renders, the decorators are applied in this order:

- Global Decorators: Applied first, in the order they’re defined.
- Component Decorators: Applied next, also in the order they’re defined.
- Story Decorators: Applied last. These are applied starting with the innermost decorator and working outwards.

---

*If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.*

*Muchas gracias!*

*Follow me for more content like this.*

*[X](https://twitter.com/edca3911) | [PeakD](https://peakd.com/@simplestack) | [Rumble](https://rumble.com/user/simplestack) | [YouTube](https://www.youtube.com/@simple-stack-by-ed) | [Linked In](https://www.linkedin.com/in/edwardcasanova/) | [GitHub](https://github.com/ed3899) | [PayPal.me](https://paypal.me/edca3899?country.x=MX&locale.x=es_XC) | [Medium](https://medium.com/@ed.wacc1995/subscribe)*

*Down below you can find other ways to tip my work.*

```
BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"
```
properties (22)
authorsimplestack
permlinkstorybook-how-to-use-decorators--react-examples
categorystorybook
json_metadata"{"app":"peakd/2025.3.6","format":"markdown","description":"The simple no bs guide","portfolio":true,"tags":["storybook","frontend","softwaredevelopment","nodejs","javascript","react","ui","testing","typescript","softwareengineering"],"users":["storybook","simplestack","simple-stack-by-","ed.wacc1995"],"image":["https://files.peakd.com/file/peakd-hive/simplestack/23wMURk3rTDxvP1NkpurkV7cToQDuoyvic54yXNs21rKJhWHwrJNd8SgeAPig58ij9aC1.png","https://files.peakd.com/file/peakd-hive/simplestack/23tcNzkqogwzkb9BiSNQMLw5go1qYLQzY1xrgTNX14SrXHy8i2RZvBfvLyDiKZypEVos7.png","https://files.peakd.com/file/peakd-hive/simplestack/23tSzCauiq84RezrxgHG1fuHfZb1QXWJvwkNiivTjpbY4aRQ2FQdeRUwqQLjJWA4rK8ua.png"]}"
created2025-03-28 15:43:45
last_update2025-03-28 15:43:45
depth0
children0
last_payout2025-04-04 15:43:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,816
author_reputation-7,742,141,582
root_title"Storybook — How to Use Decorators? (+ React Examples)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id141,736,557
net_rshares0