You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

@storybook/addon-controls

Package Overview
Dependencies
Maintainers
11
Versions
1267
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@storybook/addon-controls

Interact with component inputs dynamically in the Storybook UI


Version published
Weekly downloads
5M
increased by1.27%
Maintainers
11
Created
Weekly downloads
 

Package description

What is @storybook/addon-controls?

The @storybook/addon-controls package allows developers to interact with component inputs dynamically within the Storybook UI. It provides a way to edit props, slots, styles, and other arguments of the components being tested in real-time. This addon generates a user interface for tweaking these inputs without needing to write any additional code.

What are @storybook/addon-controls's main functionalities?

Dynamic Props Editing

Allows users to dynamically edit the props of a component from within the Storybook UI. The code sample shows how to set up controls for a Button component, including a color picker for the backgroundColor prop and an action logger for the onClick event.

export default {
  title: 'Button',
  component: Button,
  argTypes: {
    backgroundColor: { control: 'color' },
    onClick: { action: 'clicked' }
  },
};

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

export const Primary = Template.bind({});
Primary.args = {
  primary: true,
  label: 'Button',
};

Custom Controls

Enables the creation of custom controls for component arguments, such as dropdowns, checkboxes, and more. The code sample demonstrates how to create a select control for the 'size' prop of an Input component.

export default {
  title: 'Form/Input',
  component: Input,
  argTypes: {
    size: {
      control: {
        type: 'select',
        options: ['small', 'medium', 'large']
      }
    }
  }
};

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

export const Medium = Template.bind({});
Medium.args = {
  size: 'medium',
  placeholder: 'Type here...'
};

Live Editing of Args

Provides a way to live edit the 'args' of a story, which are the arguments that get passed to the component being rendered. The code sample shows a text control for the 'content' prop of a Panel component.

export default {
  title: 'Dashboard/Panel',
  component: Panel,
  argTypes: {
    content: { control: 'text' }
  }
};

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

export const DefaultPanel = Template.bind({});
DefaultPanel.args = {
  content: 'Default content',
};

Other packages similar to @storybook/addon-controls

Changelog

Source

8.2.0

Hold onto your hats! Storybook 8.2 has dropped, packed with a treasure trove of new features and bug fixes:

  • 🪝 New test hook beforeAll
  • 🕹️ Enhanced play function
  • 📦 Portable stories that let you use your stories in other testing tools
  • 🎁 Consolidated dependency to bring you better performance in a smaller package
  • ✨ Brand new onboarding experience to get you up to speed quicker
  • 💯 Hundreds more improvements
<details> <summary>List of all updates</summary>
  • Addon Controls: Fix saving on Windows - #28485, thanks @ghengeveld!
  • Addon Interactions: Use unique keys when rendering array nodes in panel - #28423, thanks @yannbf!
  • Addon Onboarding: Add icons for dev/test/doc to the splash screen - #28389, thanks @ghengeveld!
  • Addon Onboarding: New design and flow based on Save from Controls - #28327, thanks @ghengeveld!
  • Addon Onboarding: Trigger onboarding during init for Vue and Angular projects - #28482, thanks @ghengeveld!
  • Addon-A11y: Fix property default assignment - #27224, thanks @valentinpalkovic!
  • Angular: Allow format configuration of custom source preview - #28305, thanks @64BitAsura!
  • Angular: Allow outputPath object syntax - #28144, thanks @valentinpalkovic!
  • Angular: Cleanup types - #27189, thanks @valentinpalkovic!
  • Angular: Fix enableProdMode setting - #28415, thanks @valentinpalkovic!
  • Angular: Fix wrong detection of standalone components - #27353, thanks @dario-baumberger!
  • Angular: Introduce preserveSymlink builder option - #28145, thanks @valentinpalkovic!
  • Angular: Update outputPath default value in angular-cli-webpack.js - #28418, thanks @valentinpalkovic!
  • Babel: Ensure story files not transpiled earlier than ES2017 - #28469, thanks @kasperpeulen!
  • Blocks: Fix reference to storybook core - #28422, thanks @yannbf!
  • Blocks: Prebundle tocbot - #28318, thanks @shilman!
  • Build: Change require/import order, so that import has higher prio if both are specified - #27730, thanks @kasperpeulen!
  • Build: Ignore ts stories in cra/default-js sandbox - #28354, thanks @valentinpalkovic!
  • CLI: Add --no-dev option to init - #26918, thanks @fastfrwrd!
  • CLI: Add optional --dev and --no-dev options to storybook init CLI - #26918, thanks @fastfrwrd!
  • CLI: Add support for Nuxt to project init - #26884, thanks @tobiasdiez!
  • CLI: Fix CLI always asking all automigrations - #28238, thanks @ndelangen!
  • CLI: Improve error message when fetching CLI version - #28289, thanks @yannbf!
  • CLI: Include @storybook/addon-svelte-csf when initializing new projects - #27070, thanks @benmccann!
  • CLI: Prebundle get-npm-tarball-url and @ndelangen/get-tarball - #28481, thanks @ndelangen!
  • Config: Apply JavaScript-only story glob extensions for JavaScript projects - #28338, thanks @valentinpalkovic!
  • Controls: Fix date picker control validation and assignment - #26695, thanks @leeovictor!
  • Controls: Fix grouped Radio controls to have the same name - #23374, thanks @srapilly!
  • Controls: Throttling makes Color control lagging - #22615, thanks @gitstart!
  • Core: Add context as a property of the context (self-referencing) - #28353, thanks @kasperpeulen!
  • Core: Add support for beforeAll hook - #28255, thanks @ghengeveld!
  • Core: Fix startup hang caused by watchStorySpecifiers - #27016, thanks @heyimalex!
  • Core: Make sure StorybookError message shows up in browser console and interactions panel - #28464, thanks @kasperpeulen!
  • Core: Migrate from pkg-dir to fd-package-json - #28270, thanks @43081j!
  • Core: Refactor phases to run in order loading -> rendering -> playing - #28431, thanks @kasperpeulen!
  • Core: Remove more .stories.mdx handling - #25973, thanks @JReinhold!
  • Core: Remove util dependency - #28191, thanks @43081j!
  • CPC: Add CJS for core/components - #28440, thanks @ndelangen!
  • CPC: Core Package Consolidation - #27039, thanks @ndelangen!
  • CSF: Automatically extract componentPath - #24396, thanks @shilman!
  • CSF: Rename preview.js globals to initialGlobals - #27517, thanks @shilman!
  • Dependencies: Allow esbuild version 0.21.x - #28245, thanks @edoardocavazza!
  • Dependency: bump markdown-to-jsx to v7.4.5 - #26694, thanks @xyy94813!
  • Dependency: Bump Express.js - #26680, thanks @valentinpalkovic!
  • Dependency: Remove node-fetch - #28160, thanks @yk-kd!
  • Dependency: Upgrade webpack-virtual-modules to 0.6.0 - #27102, thanks @fyodorovandrei!
  • Deps: Migrate from read-pkg-up to fd-package-json - #28272, thanks @43081j!
  • Docs-tools: Replace doctrine with jsdoc-type-pratt-parser - #26305, thanks @43081j!
  • Docs: Filter mount stories from Stories block, error when referenced in MDX - #28434, thanks @kasperpeulen!
  • Docs: Fix Typeset Doc block fontSizes type - #26475, thanks @noranda!
  • Index: Fix MDX to override project-level autodocs - #28461, thanks @shilman!
  • Indexer: Improve locating stories with specials chars in path - #22110, thanks @jankoritak!
  • Next: Set default targets for next babel config - #28443, thanks @kasperpeulen!
  • Next.js: Set env.bugfixes in SWC so destructuring is never transpiled - #28363, thanks @kasperpeulen!
  • React: Export ButtonProps and HeaderProps in CLI templates - #28487, thanks @valentinpalkovic!
  • SWC: Set default targets for swc that align with our esbuild targets - #28435, thanks @kasperpeulen!
  • Telemetry: Stop prompting about crash reports in CI - #28433, thanks @yannbf!
  • Test: Add args to mount in react, svelte, and vue renderers - #28385, thanks @kasperpeulen!
  • Test: Add mount property to the story context - #28383, thanks @kasperpeulen!
  • Test: Enhance the context with canvas when the test package is used - #28368, thanks @kasperpeulen!
  • Test: Improve MountMustBeDestructuredError error message - #28468, thanks @kasperpeulen!
  • Test: Reactive spies preserve the this instance - #28445, thanks @kasperpeulen!
  • Types: Fix type implementation for CompatibleString - #27180, thanks @sni-J!
  • Vite: Fix asset warning by externalizing sb-common-assets font - #27110, thanks @valentinpalkovic!
  • Vue3: Enable new hydration mismatch compile time flag - #27192, thanks @Cherry!
  • Webpack5/Vite: Fix sourcemaps - #27171, thanks @valentinpalkovic!
</details>

Readme

Source

Storybook Controls Addon

Storybook Controls gives you a graphical UI to interact with a component's arguments dynamically, without needing to code. It creates an addon panel next to your component examples ("stories"), so you can edit them live.

Framework Support

Screenshot

Installation

Controls is part of essentials and so is installed in all new Storybooks by default. If you need to add it to your Storybook, you can run:

npm i -D @storybook/addon-controls

Then, add following content to .storybook/main.js:

export default {
  addons: ['@storybook/addon-controls'],
};

Usage

The usage is documented in the documentation.

FAQs

How will this replace addon-knobs?

Addon-knobs is one of Storybook's most popular addons with over 1M weekly downloads, so we know lots of users will be affected by this change. Knobs is also a mature addon, with various options that are not available in addon-controls.

Therefore, rather than deprecating addon-knobs immediately, we will continue to release knobs with the Storybook core distribution until 7.0. This will give us time to improve Controls based on user feedback, and also give knobs users ample time to migrate.

If you are somehow tied to knobs or prefer the knobs interface, we are happy to take on maintainers for the knobs project. If this interests you, please get in touch with us in the #contributing Discord channel.

How do I migrate from addon-knobs?

If you're already using Storybook Knobs you should consider migrating to Controls.

You're probably using it for something that can be satisfied by one of the cases described above.

Let's walk through two examples: migrating knobs to auto-generated args and knobs to custom args.

Knobs to auto-generated args

First, let's consider a knobs version of a basic story that fills in the props for a component:

import { text } from '@storybook/addon-knobs';
import { Button } from './Button';

export const Basic = () => <Button label={text('Label', 'hello')} />;

This fills in the Button's label based on a knob, which is exactly the auto-generated use case above. So we can rewrite it using auto-generated args:

export const Basic = (args) => <Button {...args} />;
Basic.args = { label: 'hello' };
Knobs to manually-configured args

Similarly, we can also consider a story that uses knob inputs to change its behavior:

import { number, text } from '@storybook/addon-knobs';

export const Reflow = () => {
  const count = number('Count', 10, { min: 0, max: 100, range: true });
  const label = text('Label', 'reflow');
  return (
    <>
      {[...Array(count)].map((_, i) => (
        <Button key={i} label={`button ${i}`} />
      ))}
    </>
  );
};

And again, as above, this can be rewritten using fully custom args:

export const Reflow = ({ count, label, ...args }) => (
  <>
    {[...Array(count)].map((_, i) => (
      <Button key={i} label={`${label} ${i}`} {...args} />
    ))}
  </>
);

Reflow.args = {
  count: 3,
  label: 'reflow',
};

Reflow.argTypes = {
  count: {
    control: {
      type: 'range',
      min: 0,
      max: 20,
    },
  },
};

My controls aren't being auto-generated. What should I do?

There are a few known cases where controls can't be auto-generated:

  • You're using a framework for which automatic generation isn't supported
  • You're trying to generate controls for a component defined in an external library

With a little manual work you can still use controls in such cases. Consider the following example:

import { Button } from 'some-external-library';

export default {
  title: 'Button',
  argTypes: {
    label: { control: 'text' },
    borderWidth: { control: { type: 'number', min: 0, max: 10 } },
  },
};

export const Basic = (args) => <Button {...args} />;

Basic.args = {
  label: 'hello',
  borderWidth: 1,
};

The argTypes annotation (which can also be applied to individual stories if needed), gives Storybook the hints it needs to generate controls in these unsupported cases. See control annotations for a full list of control types.

It's also possible that your Storybook is misconfigured. If you think this might be the case, please search through Storybook's Github issues, and file a new issue if you don't find one that matches your use case.

How can I disable controls for certain fields on a particular story?

The argTypes annotation can be used to hide controls for a particular row, or even hide rows.

Suppose you have a Button component with borderWidth and label properties (auto-generated or otherwise) and you want to hide the borderWidth row completely and disable controls for the label row on a specific story. Here's how you'd do that:

import { Button } from 'button';

export default {
  title: 'Button',
  component: Button,
};

export const CustomControls = (args) => <Button {...args} />;
CustomControls.argTypes = {
  borderWidth: { table: { disable: true } },
  label: { control: { disable: true } },
};

Like story parameters, args and argTypes annotations are hierarchically merged, so story-level annotations overwrite component-level annotations.

How do controls work with MDX?

When importing stories from your CSF file into MDX, controls will work the same way. See the documentation for examples.

Keywords

FAQs

Package last updated on 10 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc