Skip to content

Instantly share code, notes, and snippets.

@kylegach
Last active March 23, 2022 15:50
Show Gist options
  • Save kylegach/c529189196258a3c98cc8f2bfbd3c50b to your computer and use it in GitHub Desktop.
Save kylegach/c529189196258a3c98cc8f2bfbd3c50b to your computer and use it in GitHub Desktop.
Storybook Canvas Doc Block that respects viewport parameters

import { Button } from "./Button";

<Meta title="Example/Button" component={Button} parameters={{ docs: { inlineStories: false, }, viewport: { defaultViewport: "mobile1", }, }} />

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

{Template.bind({})}
import * as React from "react";
import { Canvas as SBCanvas, DocsContext } from "@storybook/addon-docs";
import { viewports } from "./viewports";
export const Canvas = (props) => {
// You can access `parameters` from DocsContext
const context = React.useContext(DocsContext);
/**
* If `parameters.viewport.defaultViewport is set to a key of `viewports`,
* apply that width to the rendered Canvas
*/
const viewport = context.parameters?.viewport?.defaultViewport;
const width = viewports[viewport]?.styles.width;
return <SBCanvas {...props} style={{ width }} />;
};
import { Meta, Story } from "@storybook/addon-docs";
import { Canvas } from "./Canvas";
import { viewports } from "./viewports";
export const parameters = {
docs: {
// See: https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/theming.md#mdx-component-overrides
components: {
Canvas,
/**
* These next two aren't strictly necessary for the technique, but
* anything you define here doesn't need imported in your mdx file, which
* I find convenient.
*/
Meta,
Story,
},
},
viewport: {
viewports,
},
};
import { MINIMAL_VIEWPORTS } from "@storybook/addon-viewport";
/**
* These are just the defaults, re-exported so I could have a stable reference
* in both `preview.js` & `Canvas.js`.
*
* See:
* - https://storybook.js.org/docs/react/essentials/viewport#use-a-detailed-set-of-devices
* - https://github.com/storybookjs/storybook/blob/next/addons/viewport/src/defaults.ts#L167-L192
*/
export const viewports = MINIMAL_VIEWPORTS;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment