DEV Community

Cover image for Storybook : develop React components in isolation | Part-2
Shahjada Talukdar
Shahjada Talukdar

Posted on • Updated on

Storybook : develop React components in isolation | Part-2

On the Part-1 of this series Storybook : develop React components in isolation | Part-1 , we talked about how we can setup Storybook and start working for our awesome UI-components Library.

Today we will see how we can create our first UI component and add it to Storybook. We will also see how we can see variations for the same component.

I will remove the welcome file src/stories/0-Welcome.stories.js which was created by the tool. Now our app structure looks like below-

Alt Text

Let's create a new component inside src/components/Spinner.js file.

I will use styled-components to style this new component. To read about style-components, please read my another article Style React component with styled-components : Part-1

Our new Spinner component's code is here πŸ‘‡

import React, { Component } from "react";
import styled from "styled-components";

const StyledSpinner = styled.div`
  border: 16px solid ${props => props.color || "red"};
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
`;

class Spinner extends Component {
  render() {
    const { color } = this.props;
    return <StyledSpinner color={color} />;
  }
}

export default Spinner;

Enter fullscreen mode Exit fullscreen mode

Cool, our component is done. Now we need to add this to the Storybook tool to visualise.

I am gonna create a new file src/stories/2-Spinner.stories.js and will import Spinner component here export default UI options so that Storybook tool can pick up it.

import React from "react";
import Spinner from "../components/Spinner";

export default {
  title: "Spinner"
};

export const byDefault = () => <Spinner />;
Enter fullscreen mode Exit fullscreen mode

Now if we run yarn storybook on terminal, we can see this πŸ‘‡ on our browser!

Alt Text

Tada πŸŽ‰
We can now see and test our new component inside the Storybook tool.

I will add few more variations for this, so that we can see how it will look if we change the props.

export const blue = () => <Spinner color="blue" />;

export const orange = () => <Spinner color="orange" />;
Enter fullscreen mode Exit fullscreen mode

After adding this code ☝️, if we now go to the browser we can see total 3 variations for the same Component.

Alt Text

Awesome!

On the next part, I will write about Addons and other cool stuff.

Till then,Cheers
πŸ‘‹

As I am trying to contribute contents on the Web, you can buy me a coffee for my hours spent on all of these ❀️😊🌸
Buy Me A Coffee

My Blog: https://shahjada.me

Top comments (0)