32
loading...
This website collects cookies to deliver better user experience
npx create-react-app storybook-project
Note: storybook-project
will be the name of our directory, but you can replace yours with whatever name you like.
storybook-project
and run the command:npx sb init
yarn storybook
to get storybook running locally.If you encounter challenges getting storybook to run, delete the yarn.lock
and node modules of your project then run yarn
again.
yarn storybook
, you'll see the Storybook interface show up in your browser. A .storybook
folder with some settings.
For now, we don't need to make edits to this folder. The main thing to take note of is that for components to show up in storybook, you need a .stories.js
file extension. You can equally have a .jsx, .ts, .tsx
file extension.
All stories are in the stories folder in the src
directory.
Button, Header and Page. stories files
. You'd notice a pattern, each of these files have an export default with a Title and Component. 'Example/Page'
is what groups each of these components under the Example group that we saw earlier.These multiple states of a single component are what we define as a story.
In code, a story is a function that returns a component’s state given a set of arguments. It is a named exports at the bottom of the stories file
Button
component- A default story and a disabled story.Button.jsx
file within the stories directory.import React from 'react';
export function Button({disabled, children} ) {
return (
<button
disabled={disabled}
style={{
padding: 12,
fontSize: 12,
background: disabled ? 'lightgray' : 'green',
color: disabled ? 'gray' : 'white',
}}
>
{children}
</button>
);
}
Button.stories.jsx
file to build the 2 stories- default story and disabled story. Don't forget to export default and specify the title and the component.import React from 'react';
import { Button } from './Button';
export default {
title: 'Components / Button',
component: 'Button',
};
export const Default = () => <Button>Click me</Button>
export const Disabled = () => <Button disabled>Don't click me</Button>;
disabled
argType and specify the control as a boolean (since this is going to be either true or false).text
. See code below:import React from 'react';
import { Button } from './Button';
export default {
title: 'Components / Button',
component: 'Button',
argTypes: {
disabled: { control: 'boolean' },
children: { control: 'text' },
},
};
export const Default = (args) => <Button {...args} />;
Default.args = {
disabled: false,
children: 'Click me',
};
export const Disabled = (args) => <Button {...args} />;
Disabled.args = {
disabled: true,
children: "Don't click me",
};
For a video tutorial, watch learn Storybook in 8mins