Join live session: Top 8 Storybook myths holding your team back
Docs
Storybook Docs

Toolbars & globals

Watch a video tutorial

Storybook ships with toolbar addons to control the viewport and background the story renders in. You can also create your own toolbar items which control special “globals” which you can then read to create decorators to control story rendering.

Globals

Globals in Storybook represents “global” (as in not story-specific) inputs to the rendering of the story. As they aren’t specific to the story, they aren’t passed in the args argument to the story function (although they are accessible as context.globals), but typically you use them in decorators, which apply to all stories.

When the globals change, the story re-renders, and the decorators rerun with the new values. The easiest way to change globals is to create a toolbar item for them.

Global types and the toolbar annotation

Storybook has a simple, declarative syntax for configuring toolbar menus. In your .storybook/preview.js, you can add your own toolbars by creating globalTypes with a toolbar annotation:

.storybook/preview.js
export const globalTypes = {
  theme: {
    name: 'Theme',
    description: 'Global theme for components',
    defaultValue: 'light',
    toolbar: {
      icon: 'circlehollow',
      // Array of plain string values or MenuItem shape (see below)
      items: ['light', 'dark'],
      // Property that specifies if the name of the item will be displayed
      showName: true,
      // Change title based on selected value
      dynamicTitle: true,
    },
  },
};

As globals are global you can only set globalTypes in .storybook/preview.js.

When you start your Storybook, you should see a new dropdown with the light and dark options in your toolbar.

Create a decorator

We have a global implemented. Let's wire it up! We can consume our new theme global in a decorator using the context.globals.theme value.

For example, suppose you are using styled-components. You can add a theme provider decorator to your .storybook/preview.js config:

.storybook/preview.js
import { ThemeProvider } from 'styled-components';
 
import { MyThemes } from '../my-theme-folder/my-theme-file'
 
// Function to obtain the intended theme
const getTheme = (themeName) => {
  return MyThemes[themeName]
}
 
const withThemeProvider=(Story,context)=>{
  const theme = getTheme(context.globals.theme);
  return (
    <ThemeProvider theme={theme}>
      <Story />
    </ThemeProvider>
  )
}
export const decorators = [withThemeProvider];

Advanced usage

So far, we've managed to create and consume a global inside Storybook.

Now let's take a look at a more complex example. Let's suppose we wanted to implement a new global called locale for internationalization, which shows a flag on the right side of the toolbar.

In your .storybook/preview.js, add the following:

.storybook/preview.js
export const globalTypes = {
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'en',
    toolbar: {
      icon: 'globe',
      items: [
        { value: 'en', right: '🇺🇸', title: 'English' },
        { value: 'fr', right: '🇫🇷', title: 'Français' },
        { value: 'es', right: '🇪🇸', title: 'Español' },
        { value: 'zh', right: '🇨🇳', title: '中文' },
        { value: 'kr', right: '🇰🇷', title: '한국어' },
      ],
    },
  },
};

The icon element used in the examples loads the icons from the @storybook/components package. See here for the list of available icons that you can use.

The @storybook/addon-toolbars addon is required to use toolbars. The toolbars addon is included by default in @storybook/addon-essentials.

By adding the configuration element right, the text will be displayed on the right side in the toolbar menu once you connect it to a decorator.

Here's a list of the configuration options available.

MenuItemTypeDescriptionRequired
valueStringThe string value of the menu that gets set in the globalsYes
titleStringThe main text of the titleYes
leftStringA string that gets shown on the left side of the menuNo
rightStringA string that gets displayed on the right side of the menuNo
iconStringAn icon that gets shown in the toolbar if this item is selectedNo

Consuming globals from within a story

We recommend consuming globals from within a decorator and define a global setting for all stories.

But we're aware that sometimes it's more beneficial to use toolbar options on a per-story basis.

Using the example above, you can modify any story to retrieve the Locale global from the story context:

MyComponent.stories.js|jsx|ts|tsx
import React from 'react';
 
import { MyComponent } from './MyComponent';
 
export default {
  /* 👇 The title prop is optional.
  * See https://storybook.js.org/docs/6/configure#configure-story-loading
  * to learn how to generate automatic titles
  */
  title: 'MyComponent',
  component: MyComponent,
};
 
const getCaptionForLocale = (locale) => {
  switch (locale) {
    case 'es':
      return 'Hola!';
    case 'fr':
      return 'Bonjour!';
    case 'kr':
      return '안녕하세요!';
    case 'zh':
      return '你好!';
    default:
      return 'Hello!';
  }
};
 
export const StoryWithLocale = (args, { globals: { locale } }) => {
  const caption = getCaptionForLocale(locale);
  return <>{caption}</>;
};

In Storybook 6.0, if you set the global option passArgsFirst: false for backward compatibility, the story context is passed as the first argument:

MyComponent.stories.js|jsx|ts|tsx
export const StoryWithLocale = ({ globals: { locale } }) => {
  const caption = getCaptionForLocale(locale);
  return <>{caption}</>;
};

Consuming globals from within an addon

If you're working on a Storybook addon and need to retrieve globals, you can do so. The @storybook/api package provides a hook for this scenario. You can use the useGlobals() hook to retrieve any globals you want.

Using the ThemeProvider example above, you could expand it to display which theme is active inside a panel as such:

your-addon-register-file.js
import React from 'react';
 
import { useGlobals } from '@storybook/api';
 
import { AddonPanel, Placeholder, Separator, Source, Spaced, Title } from '@storybook/components';
 
import { MyThemes } from '../my-theme-folder/my-theme-file';
 
// Function to obtain the intended theme
const getTheme = (themeName) => {
  return MyThemes[themeName];
};
 
const ThemePanel = (props) => {
  const [{ theme: themeName }] = useGlobals();
 
  const selectedTheme = getTheme(themeName);
 
  return (
    <AddonPanel {...props}>
      {selectedTheme ? (
        <Spaced row={3} outer={1}>
          <Title>{selectedTheme.name}</Title>
          <p>The full theme object</p>
          <Source
            code={JSON.stringify(selectedTheme, null, 2)}
            language="js"
            copyable
            padded
            showLineNumbers
          />
        </Spaced>
      ) : (
        <Placeholder>No theme selected</Placeholder>
      )}
    </AddonPanel>
  );
};

Updating globals from within an addon

If you're working on a Storybook addon that needs to update the global and refreshes the UI, you can do so. As mentioned previously, the @storybook/api package provides the necessary hook for this scenario. You can use the updateGlobals function to update any global values you need.

Also, you can use both @storybook/addons and @storybook/core-events packages together to trigger the refresh.

For example, if you were working on a toolbar addon, and you want to refresh the UI and update the global once the user clicks on a button:

your-addon-register-file.js
import React, { useCallback } from 'react';
 
import { FORCE_RE_RENDER } from '@storybook/core-events';
import { useGlobals } from '@storybook/api';
 
import { IconButton, Icons } from '@storybook/components';
 
import { addons } from '@storybook/addons';
 
const ExampleToolbar = () => {
  const [globals, updateGlobals] = useGlobals();
 
  const isActive = globals['my-param-key'] || false;
 
  // Function that will update the global value and trigger a UI refresh.
  const refreshAndUpdateGlobal = () => {
    // Updates Storybook global value
    updateGlobals({
      ['my-param-key']: !isActive,
    }),
      // Invokes Storybook's addon API method (with the FORCE_RE_RENDER) event to trigger a UI refresh
      addons.getChannel().emit(FORCE_RE_RENDER);
  };
 
  const toggleOutline = useCallback(() => refreshAndUpdateGlobal(), [isActive]);
  
  return (
    <IconButton
      key="Example"
      active={isActive}
      title="Show a Storybook toolbar"
      onClick={toggleOutline}
    >
      <Icons icon="outline" />
    </IconButton>
  );
};