Back to integrations
Add your integration
Categories
  • ⭐️ Popular
  • 🧩 Essentials
  • 🛠 Code
  • ⚡️ Data & state
  • ✅ Test
  • 💅 Style
  • 🎨 Design
  • ⚙️ Appearance
  • 🗄 Organize
How to install addons Create an addon
storybook-react-context
Manipulate React context inside Storybook. Read state and dispatch updates from outside of React component.
npm install storybook-react-context
Last updated about 2 years ago
18.9k
Downloads per week
Readme View on GitHub

storybook-react-context

Manipulate React context inside Storybook. Read state and dispatch updates from outside of React component.

React examples

Install

npm install -D storybook-react-context

Usage

Add withReactContext decorator where needed, per component or globally.

import { withReactContext } from 'storybook-react-context';

export default {
  title: 'some story',
  decorators: [withReactContext],
};

The decorator can also be preconfigured for all stories in the module:

export default {
  title: 'some story',
  decorators: [
    withReactContext({
      Context: ExampleContext,
      initialState: { authenticated: false },
    }),
  ],
};

Options

withReactContext takes an argument which is an object with the following optional properties:

  • Context - The context returned by React.createContext to provide for story's components
  • reducer(state, action) - custom reducer to produce the provider value or;
  • useProviderValue(state, args) - a function (hook) to be used to derive the provider value (provides story args as second argument to link with Storybook Controls)
  • initialState - the initial state to use for the provider value

The decorator options can also be se set in story parameters using reactContext key:

someComponent.parameters = {
  reactContext: {
    initialState: {
      defaultValue: true,
    },
    reducer: (state, action) => ({ ...state, action })
  }
};

Component will be wrapped with another component which uses the context hook and returns it to the story via story context as the result of React.useReducer with reducer function and initialState.

The useProviderValue hook can be used to link the context with Storybook Controls.

import { withReactContext } from 'storybook-react-context';

export const myStory = ({ myValue }) => (
  <button onClick={() => dispatch({ text: 'Changed' })}>{state.text}</button>
);
myStory.args = {
  myValue: true,
}
myStory.decorators = [withReactContext];
myStory.parameters.reactContextState = {
  useProviderValue: (state, args) => args
};
Join the community
6,587 developers and counting
WhyWhy StorybookComponent-driven UI
DocsGuidesTutorialsChangelogTelemetryStatus
CommunityAddonsGet involvedBlog
ShowcaseExploreProjectsComponent glossary
Open source software
Storybook

Maintained by
Chromatic
Special thanks to Netlify and CircleCI