Storybook: Is it possilbe to use React.createContext with addon-contexts?

Created on 4 Jun 2020  路  2Comments  路  Source: storybookjs/storybook

I'd like to use React.createContext with addon-contexts. I've only seen examples with ThemeProvider from "styled-components".

I'd like to be able to update a provider value from the storybook UI and access that value in my stories, ideally globally with a decorator.

I've tried the below but updating the ui given by addon-contexts dosn't update the react context value in ThemeDecorator

//contexts.js
import ThemeContext from "./ThemeContext";

export const contexts = [
  {
    icon: "box", // a icon displayed in the Storybook toolbar to control contextual props
    title: "hereiam", // an unique name of a contextual environment
    components: [
      ThemeContext.Provider, // a react context
    ],
    params: [
      // an array of params contains a set of predefined `props` for `components`
      { name: "Light Theme", props: { theme: "day" } },
      {
        name: "Dark Theme",
        props: { theme: "night" /* : your dark theme */ },
        default: true,
      },
    ],
    options: {
      deep: true, // pass the `props` deeply into all wrapping components
      disable: false, // disable this contextual environment completely
      cancelable: false, // allow this contextual environment to be opt-out optionally in toolbar
    },
  },
  /* ... */ // multiple contexts setups are supported
];
import React, { useContext } from "react";
import ThemeContext from "./ThemeContext";

const ThemeDecorator = (storyFn) => {
  const { theme } = useContext(ThemeContext);
  console.log("theme", theme); // this value does not change
  return <div className=`ax-theme--${theme}`>{storyFn()}</div>;
};

export default ThemeDecorator;

// ThemeContext.js
import React from "react";
const ThemeContext = React.createContext({ theme: "day" });

export default ThemeContext;
//preview.js
import { addDecorator } from "@storybook/react";
import { withContexts } from "@storybook/addon-contexts/react";
import { contexts } from "./contexts";
import ThemeDecorator from "./ThemeDecorator";

addDecorator(ThemeDecorator);
addDecorator(withContexts(contexts));
contexts react question / support

All 2 comments

Highly recommend upgrading to addon-toolbars: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-addon-contexts

Amazing that worked great and first time. Thanks and thanks in general for answering this issues.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmmarmol picture dmmarmol  路  57Comments

EdenTurgeman picture EdenTurgeman  路  81Comments

hckhanh picture hckhanh  路  69Comments

43081j picture 43081j  路  61Comments

p3k picture p3k  路  61Comments