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));
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.