How to add a global decorator in Storybook

Viewed 5575

In ReactJs project you can use .storybook/preview.js file to add global decorators and parameters. How to achieve this same behaviour with @storybook/react-native?

What I need is to wrap all my stories with ThemeProvider but the unique way that I found is to wrap individual stories with .addDecorator().

2 Answers

Edit storybook/index.js, by using addDecorator on it.

Example:

import React from 'react'
import { getStorybookUI, configure, addDecorator } from '@storybook/react-native'
import Decorator from './Decorator'


addDecorator(storyFn => (
  <Decorator>
    {storyFn()}
  </Decorator>
))

// import stories
configure(() => {
  require('../stories')
}, module)


const StorybookUI = getStorybookUI({ onDeviceUI: true })
export default StorybookUI;;

As of June 2021, using storybook v5.3.25, the above answer does not work. However I have managed to figure out a solution.

Decorators must be added to the storybook/index.js file in the following format:

import { ThemeDecorator } from './storybook/ThemeDecorator';

addDecorator(withKnobs); // inbuilt storybook addon decorator
addDecorator(ThemeDecorator);// custom decorator

configure(() => {
  loadStories();
}, module);

in this instance, ThemeDecorator.js is a simple wrapper component that renders your story, it would look something like this:

import React from 'react';
import { Provider } from 'theme-provider';

export const ThemeDecorator = (getStory) => (
  <Provider>{getStory()}</Provider>
);

Importantly, the addDecorator function expects a React component (not a wrapper function as other examples claim), that it will render, with its props being a reference to an individual story at runtime.

Related