Storybook in ReactJs
Tags: react, webdev, javascript, frontend
Published: 2021-09-28 07:09:23

---
title: Storybook in ReactJs
published: true
description: create organize UI and self documented component.
tags: #react #webdev #javascript #frontend
cover_image: https://placid.app/u/uzhd1?hl=Storybook&subline=Development%20environment%20for%20UI%20components&img=%24PIC%24https%3A%2F%2Fmadewithnetworkfra.fra1.digitaloceanspaces.com%2Fspatie-space-production%2F1830%2Fdemo.f13d28a7.gif
---
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.
```sh
$ npx sb init
```

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:
```sh
$ yarn storybook
```
it will open up a new tab similar like this ![Screenshot 2021-09-19 at 03.32.56](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyx7sjkwaa0he87zyp7o.png)
 


### Button Component Code
great, now let's create a button component:

```jsx
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
```
### 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`:

```jsx
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",
};

```
The default export metadata controls how the Storybook lists your stories.
Use the named exports of a [CSF (Component Story Format)](https://storybook.js.org/docs/react/api/csf) file to define your story. `args` is argument (`props`) pass  in  to component.

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d50c74eqih6501jxka4.gif)
 
### in-depth

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

```jsx
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 />,
};

```

- ***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. 

```js
color: {
   control: {
      type: 'select',
      options: ['primary', 'secondary']
   }
}
```

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jybu6yx0xx5jhwt63c2.gif)

## 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