npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

storybook-react-context

v0.7.0

Published

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

Downloads

108,417

Readme

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,
      contextValue: { authenticated: false },
    }),
  ],
};

or via parameters:

export default {
  title: 'some story',
  decorators: [withReactContext],
  parameters: {
    reactContext: {
      context: ExampleContext,
      contextValue: { authenticated: false },
    },
  },
};

NB: Avoid using the same context parameter for reactContext as in the default export of the story. This will cause a maximum call stack size exceeded error.

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
  • contextValue - the value to use for the provider value. If a function is provided, it will be called with the story context as the first argument. The function can return React hooks such as useState of useReducer to manage the state in the story definition.
  • contexts - an array of context options (an object with context and contextValue properties) to provide multiple contexts for story's components

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

export default {
  title: 'My Component',
  component: MyComponent,
  decorators: [withReactContext],
};

// single provider is used for `MyComponent`
const SomeStory = {
  parameters: {
    reactContext: {
      context: FirstContext,
      contextValue: { someContextValue: true },
    },
  },
}

// multiple provider are used wrapping the `MyComponent` component
const AnotherStory = {
  parameters: {
    reactContext: {
      contexts: [
        {
          context: FirstContext,
          contextValue: { someContextValue: true },
        },
        {
          context: SecondContext,
          contextValue: [1, 2, 3],
        }
      ]
    },
  },
}

The component or the result of the render function will be wrapped with providers setting the value to the result of contextValue. The context values are passed back to the story render function in the story context (second argument) in reactContext property. The property contains two properties: values and value. The values property is an array of all values provided for each context. The value property returns the last value and is useful for single contexts.

import * as React from 'react';
import { withReactContext } from 'storybook-react-context';

const reducer = (state, action) => ({ ...state, ...action });

// the values are arrays as we expect a setter/dispatch function as second argument in some of the stories
const FirstContext = React.createContext([{ text: 'Initial text' }]);
const SecondContext = React.createContext(['black']);

const MyComponent = () => {
  const [textState] = React.useContext(FirstContext);
  const [colorState] = React.useContext(SecondContext);

  return <div style={{ color: colorState }}>{textState?.text}</div>;
};

export default {
  title: 'My Component',
  component: MyComponent,
  decorators: [withReactContext],
};

// access the reducer dispatch function set in the contextValue parameter from the story
export const FirstStory = {
  render: (_, { reactContext }) => {
    const [, dispatch] = reactContext.value;
    return (
      <>
        <MyComponent />
        <button onClick={() => dispatch({ text: 'Changed text' })}>Change text</button>
      </>
    );
  },
  parameters: {
    reactContext: {
      context: FirstContext,
      contextValue: () => React.useReducer(reducer, { text: 'Initial text' }),
    },
  },
};

// apply multiple contexts and use `reactContext.values` to access the setters from the story
export const SecondStory = {
  render: (_, { reactContext }) => {
    const [, [color, setFirstContextValue]] = reactContext.values;
    const colors = ['red', 'orange', 'blue', 'green', 'purple'];
    return (
      <>
        <MyComponent />
        <p>Selected color: {color}</p>
        <button
          onClick={() => {
            const randomColor = colors[Math.floor(Math.random() * colors.length)];
            return setFirstContextValue(randomColor);
          }}
        >
          Toggle Value
        </button>
      </>
    );
  },
  parameters: {
    reactContext: {
      contexts: [
        {
          context: FirstContext,
          contextValue: [{ text: 'New text' }],
        },
        {
          context: SecondContext,
          contextValue: () => React.useState(),
        },
      ],
    },
  },
};

// use story controls (args) to set the context value
export const ThirdStory = {
  args: { text: 'Initial text' },
  parameters: {
    reactContext: {
      context: FirstContext,
      contextValue: ({ args }) => [
        {
          text: args.text,
        },
      ],
    },
  },
};

The contextValue function provides the story context as its first argument. This gives access to story args and other context values. In addition, the useArgs hook from @storybook/preview-api is exposed to access and update the args within the story.

See the example stories for more.