DEV Community

Cover image for Storybook in ReactJs
HasOne
HasOne

Posted on

Storybook in ReactJs

Storybook is javascript package that helps developer to create organize UI that's self documented, make the developing and building process efficient. once we have created component and we add it to story, so we have example of how our component looks like and the features we can add and help us improve the component. if other developer working on the same team, in case her/she need search component, and you have already made search component, so he can use it and can change according he/her need. it helps to stop recreate same component. so let's get started;

installation

let's install the storybook in our in react project, assuring you already have installed react.

$ npx sb init
Enter fullscreen mode Exit fullscreen mode

once it's done you will see a stories directory insdie src/, this is where we will create our stories. now let's spin up the storybook:

$ yarn storybook
Enter fullscreen mode Exit fullscreen mode

it will open up a new tab similar like this Screenshot 2021-09-19 at 03.32.56

Button Component Code

great, now let's create a button component:

import React from 'react'
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import CustomButton from '@material-ui/core/Button';
import GridItem from '@material-ui/core/Grid';
import LoopIcon from '@material-ui/icons/Loop';

const Button = (props) => {

    const {
        styleContainer,
        value,
        onClick,
        color,
        variant,
        fullWidth,
        disabled,
        classNameContainer,
        isLoading,
        startIcon,
 } = props;

    const classes = useStyles();

    return (
        <GridItem item lg={lg} md={md} sm={sm} xs={xs} className={classNameContainer}>
            <CustomButton
                onClick={onClick}
                color={color}
                variant={variant}
                fullWidth={fullWidth}
                disabled={disabled}
                className={classes.button}
                startIcon={startIcon}>
                {isLoading ? <LoopIcon className={classes.icon} /> : value}
            </CustomButton>
        </GridItem>
    )
}

const useStyles = makeStyles((theme) => ({
    button: {
        marginBottom: 10
    },
    icon: {
        animation: '$rotateIcon 1s infinite linear',
    },
    '@keyframes rotateIcon': {
        '0%': {
            transform: 'rotate(0)',
        },
        '100%': {
            transform: 'rotate(359deg)',
        },
    }
}));

Button.propTypes = {
    onClick: PropTypes.func,
    color: PropTypes.string,
    variant: PropTypes.string,
    fullWidth: PropTypes.bool,
    disabled: PropTypes.bool,
    className: PropTypes.object,
    value: PropTypes.string,
};
Button.defaultProps = {
    color: "secondary",
    variant: "contained",
    fullWidth: false,
    disabled: false,
    className: [],
    value: "...",
}

export default Button
Enter fullscreen mode Exit fullscreen mode

Story Code

Now exciting moment, let's create story inside stories directory with the same name as component's name and plus .stories, so it becomes like Button.stories.js. we should put stories.js after name: x.stories.js:

import React from "react";

import { Button } from "../components/";

export default {
  title: "Example/Button",
  component: Button,
};

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

export const Primary = Template.bind({});
Primary.args = {
  value: "Login",
};

Enter fullscreen mode Exit fullscreen mode

The default export metadata controls how the Storybook lists your stories.
Use the named exports of a CSF (Component Story Format) file to define your story. args is argument (props) pass in to component.

1

in-depth

let's create some advance story, where we do everything

import React from "react";
import { action } from "@storybook/addon-actions";
import AddIcon from "@material-ui/icons/Add";

import { Button } from "../components/";

export default {
  title: "Example/Button",
  component: Button,
  argTypes: {
    onClick: { action: "clicked" },
    color: {
      defaultValue: "primary",
      description: "type description",
      control: {
        type: "select",
        options: ["primary", "secondary"],
      },
    },
    disabled: {
      defaultValue: false,
    },
    fullWidth: { defaultValue: false },
    variant: {
      defaultValue: "contained",
      control: {
        type: "select",
        options: ["contained", "outlined"],
      },
    },
  },
};

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

export const Primary = Template.bind({});
Primary.args = {
  value: "Login",
};

export const Icon = Template.bind({});
Icon.args = {
  value: "Add New Item",
  startIcon: <AddIcon />,
};

Enter fullscreen mode Exit fullscreen mode
  • argTyps Component Level args will apply to all stories, unless it's overwritten.

  • DefaultValue you can provide default value by defaultValue: 'some value' inside object and assign it to props's name.

  • onClick if you want to detect the onClick listener, you have to import the action addon import { action } from "@storybook/addon-actions";, and the the story it's action. now you will see logs when you click on the button.

  • control if you have multiple value and you want to render it in dropdown, control object comes into play. control object takes: type property which type it should be. we need "select" and options property where we have multiple values in array.

color: {
   control: {
      type: 'select',
      options: ['primary', 'secondary']
   }
}
Enter fullscreen mode Exit fullscreen mode

2

Conclusion

Storybook is new way to create component and share across the team, you can see how your component looks like and what the improve you need to add. making the re-usable component easy and maintainable. Storybook becomes important part of front-end developer.

I hope you learnt some today. Thank you so much for reading my article, if you have anything let me know.

https://storybook.js.org/docs/react/get-started/introduction

Top comments (1)

Collapse
 
felipemimoura profile image
Felipe Moura

Storybook is a great tool, I work with that and time-design love