swjh
All posts

How to control React context from Storybook toolbar

   ⬪   2 min read
#storybook#react

You can control a react context from Storybook toolbar by creating a custom control. Here’s an example how to set up a language switch, but you could do the same with any value.
You can not just control a React Context like this but anything; in this case I also change the document lang attribute.

// .storybook/preview.tsx

import type { Preview } from "@storybook/react-vite";

const preview: Preview = {
  initialGlobals: {
    locale: "en",
  },
  globalTypes: {
    locale: {
      description: "Locale for components",
      defaultValue: "en",
      toolbar: {
        title: "Locale",
        icon: "globe",
        items: ["de", "en"],
      },
    },
  },
  decorators: [
    (Story, context) => {
      // get value from storybook control
      const lang = context.globals.locale;

      // make sure to change document language as well
      document.documentElement.lang = lang;

      // wrap story in context wrapper
      return (
        <MyContext.Provider value={{ lang }}>
          <Story />
        </MyContext.Provider>
      );
    },
  ],
};