How to use context providers in Storybook

Viewed 921

I'm wondering what the best approach would be for using using context providers in stories. At the moment, I'm passing the context's value across in args and then in a decorator passing that context to the provider, but I'm not sure if this is the right approach. Let me know what y'all reckon. This is what I've got:

A context provider:

export const SomeContext = React.createContext(false);

export const SomeContextProvider = ({ someContext, children }) => {
  return (
    <SomeContext.Provider value={someContext}>{children}</SomeContext.Provider>
  );
};

A context consumer:

export function ContextConsumer({ props }) {
  const someContext = useContext(SomeContext);

  return (
    <div>
      I'm a context consumer and someContext is {someContext ? "true" : "false"}
    </div>
  );
}

A decorator:

(Story, context) => {
    return (
      <SomeContextProvider someContext={context.args.someContext}>
        <Story />
      </SomeContextProvider>
    );
  }

A story:

const Template = (args) => <ContextConsumer {...args} />;

export const Default = Template.bind({});
Default.args = {
  someContext: true
};
0 Answers
Related