How to build a component library with React and Storybook

How to build a component library with React and Storybook

Learn how to build a component library with React and Storybook to create modular and reusable components that can be shared across projects.

Learn how to build a component library with React and Storybook to create modular and reusable components that can be shared across projects.

Storybook is a development environment for UI components. It let us browse a component library, view the different states of its components, and interactively develop and test them. Storybook runs outside of our application; therefore, we can develop UI components in isolation without worrying about any project dependencies and requirements. Throughout these series, we are going to create the components of an online banking app called Marvel Bank.

Let's start by learning how we can setup Storybook in a brand-new create-react-app project.

Setting Up Storybook

There are two options available to us for adding Storybook: we can install the platform globally or we can start the platform locally. Which installation path should we take?

Our colleague, Matt Machuga, an Engineering Lead in our R&D Team, suggests that "CLI tools that are not project specific are good candidates for global installation." In practice, Matt tries to "scope everything else into local. So the version being used is kept recorded and installed via npm install."

We have different options for installing Storybook: a global install, an install using npx, and a local manual install. I'll explore those options with you and let you decide which one is right for you. However, I do recommend that you walk with me through the local manual install as it let us learn a great deal about how Storybook works.

Install @storybook/react Globally

To install and run Storybook from your shell follow these quick steps:

  • In the shell, make sure that your project directory your current working directory, marvel-app.
  • Next, install @storybook/cli globally:
npm i -g @storybook/cli

Above, we used a few npm argument shortcuts. i stands for install and -g stands for the flag --global.

  • Restart your shell. You can do that by closing the existing window or tab and opening a new one.
  • Finally, with marvel-app again as your current working directory, run the getstorybook command to have the Storybook CLI scaffold all the necessary files and folders to work with Storybook in your project. These include the .storybook folder under the root project and the stories folder under the src folder.

Let's see how this can be done without a global install using npx.

Install @storybook/react Using npx

We can emulate the same behavior of the global installation of Storybook but without the actual global installation. If you have npm >= 5.2 installed in your system, you have npx available!

  • In the shell, make sure that your project directory your current working directory, marvel-app.
  • Run the getstorybook command using npx:
npx @storybook/cli getstorybook

[npx](https://alligator.io/workflow/npx/) downloads and executes the binary on the fly. The Storybook CLI will run and create all the necessary files and folder in your project just as in the previous section. This method is the fastest way to get up and running!

Now, let's explore what the Storybook creators call the "slow start", the local manual installation of Storybook. Through that process, we'll learn how the folders and files installed by the Storybook CLI work.

Install @storybook/react manually

In the shell, let's run the following command:

npm:

npm i -D @storybook/react

Another npm argument shortcut. -D stands for --save-dev.

Storybook NPM Script

After @storybook/react has finished its installation. We need to add the following script to package.json to run Storybook:

"storybook": "start-storybook -p 9001 -c .storybook"
{
  "name": "marvel-bank",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "node-sass-chokidar": "^1.3.3",
    "npm-run-all": "^4.1.3",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css":
      "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "storybook": "start-storybook -p 9001 -c .storybook",
    "start-react": "react-scripts start",
    "start": "npm-run-all -p watch-css start-react",
    "build-react": "react-scripts build",
    "build": "npm-run-all -s build-css build-react",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@storybook/react": "^3.4.8"
  }
}

Create A Storybook Configuration File

As explained in the Storybook docs, the platform is flexible and can be configured in different ways. We can control that configuration through a config directory. In our storybook npm script, we added a -c option followed by .storybook which tells Storybook to look for configuration options in the .storybook hidden folder.

Having our project root folder as the current working directory, let's go ahead and create that folder:

macOS/Linux/Windows:

mkdir .storybook

Next, we need to create a config.js file inside .storybook to hold the configuration. Let's start it with the following code:

// .storybook/config.js

import { configure } from "@storybook/react";

function loadStories() {
  require("../src/stories/index.js");
  // You can require as many stories as you need.
}

configure(loadStories, module);

Storybook works in a similar way to testing tools. The config.js loads the configure method, which takes as argument a function called loadStories and a module. loadStories will have stories defined on its body. A story describes the single state of a component. We want to write a story for each state a component will have.

Stories are similar to how [it](https://jestjs.io/docs/en/api.html#testname-fn-timeout) methods run tests in testing libraries like Jest.

We are going to write and load the stories from ../src/stories/index.js which will be under the root folder. Let's create such folder and file to write our first story. Under the src folder let's create a stories subfolder and then create an index.js file inside it.

.storybook is used solely for configuration files. Do not put your stories folder inside this hidden folder.

Writing a Story in Storybook

Open the recently created index.js under src/stories and populate it with the following code:

// src/stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";

So far, there's not much going on. We import React and a storiesOf method that will help us create stories for a component. We need that component. Let's import Button here:

// src/stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../../src/features/common/Button";

Storybook has a declarative language. What we are going to do next is to tell it that we want stories of Button:

// src/stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../../src/features/common/Button";

storiesOf("Button", module);

If we were thinking in terms of an actual book, this is the book's binding and cover. We need to fill it with pages full of stories. We do that declarative too using the add method:

// src/stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../../src/features/common/Button";

storiesOf("Button", module).add("with text", () => (
  <Button label={`Continue`} />
));

add acts like adding a chapter to a book that has a story. We want to give each chapter a title. In this case, we are creating a story titled with text. add takes as argument the story title and a function that renders the component being staged.

We have the foundation of writing a story. It's time to see if everything is working by running Storybook.

Running Storybook

In the shell, run the following command:

npm:

npm run storybook

If everything runs successfully, we will see this message in the shell:

info Storybook started on => http://localhost:9001/

Let's open that URL, [http://localhost:9001/](http://localhost:9001/) in the browser. Let it load... and there we have it in its full glory: our own Storybook!

Right now it's pretty basic but this is a great start!

This is a good time to make another commit to address the integration of Storybook:

git status
git add .
git commit -m "Integrate Storybook"

Integrating CSS with Storybook

To communicate the presentation and state of the Button component, we need to add styling to it. Under src/features/common, let's create Button.scss and populate it with the following code:

// src/features/common/Button.scss

@import "../../styles/theme";

.Button {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  height: 40px;
  width: 160px;
  border: 2px solid $blue;
  border-radius: 60px;

  font-family: $primary-font;
  font-size: 16px;
  color: $blue;
  letter-spacing: 1.27px;
  text-align: center;

  text-transform: uppercase;
}

Next, let's import that stylesheet into Button.js and add Button as a className for the Button component:

import React from "react";

import "./Button.css";

const Button = props => <div className="Button">{props.label}</div>;

export default Button;

Let's save our work. We should see now how Storybook has refreshed the board and shows the updated component with styling applied:

Just like with create-react-app, we can make changes to the structure, content, or style of a component and they will be updated in Storybook. Let's change the background, font color and border of Button to see this in action:

// src/features/common/Button.scss

@import "../../styles/theme";

.Button {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  background: $green;

  height: 40px;
  width: 160px;

  border-radius: 60px;

  font-family: $primary-font;
  font-size: 16px;
  color: white;
  letter-spacing: 1.27px;
  text-align: center;

  text-transform: uppercase;
}

Let's save our work again and observe the changes:

Style changes are well integrated into our workflow. It's truly amazing that we can preview our components this way without having to run our application. We can develop our component in isolation and then use them in the app whenever we want.

As discussed before, Button has three different presentations. The best way to organize that would be through CSS classes and props.

We want the Button component to know:

  • Its active state: active / disabled
  • Its style state: fill / no-fill

Let's update Button.scss with classes that represent these states:

// src/features/common/Button.scss

@import "../../styles/theme";

.Button {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  height: 40px;
  width: 160px;

  border-radius: 60px;

  font-family: $primary-font;
  font-size: 16px;

  letter-spacing: 1.27px;
  text-align: center;

  text-transform: uppercase;
}

.active {
}

.disabled {
  border: 2px solid $color-text-lighter;

  color: $color-text-lighter;
  letter-spacing: 1.64px;
}

.fill {
  background: $green;
  box-shadow: 0 6px 8px 0 rgba(103, 194, 172, 0.5);

  color: $white;
  letter-spacing: 1.61px;
}

.no-fill {
  border: 2px solid $blue;

  color: $blue;
  letter-spacing: 1.27px;
}

Let's briefly review what we are doing here since it's important how this impacts component staging in Storybook:

  • .Button has all the style properties shared by all instances of Button.
  • .active is not in use right now but it could be used to provide unique properties to an active button.
  • .disabled has the style properties for any instance of Button that becomes disabled.
  • fill and no-fill apply distinct styling to an active button.

We need to integrate this style logic into our component logic as follows:

// src/features/common/Button.js

import React from "react";

import "./Button.css";

const Button = props => (
  <div
    className={`Button ${
      props.active
        ? props.fill
          ? `active fill`
          : `active no-fill`
        : `disabled`
    }`}
  >
    {props.label}
  </div>
);

export default Button;

Using a combination of ternary operators we process the state of the button. If props.active is true, we check if props.fill is true or not and apply the corresponding class to the component. If props.active is false, there are no extra decisions to make and we apply the default disabled class.

To see this in action, let's create new stories in our Storybook!

Creating Multiple Stories for a Component in Storybook

Let's head to src/stories/index.js and remove the current story that we have defined there, with text, as it isn't telling too much of a story:

// stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../../src/features/common/Button";

storiesOf("Button", module);

Next, let's add three new stories that clearly define the three presentations that we want Button to have depending on different state flags:

// stories/index.js

import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../../src/features/common/Button";

storiesOf("Button", module)
  .add("active with fill", () => (
    <Button label={`continue`} fill={true} active={true} />
  ))
  .add("active with no fill", () => (
    <Button label={`sign up`} fill={false} active={true} />
  ))
  .add("disabled", () => <Button label={`continue`} active={false} />);

Let's save our work and we'll see Storybook update to show the three new stories under Button:

Each story renders an isolated instance of Button whose presentation depends on the props values that are passed to it. This is where we can see the value proposition of Storybook at play.

Without Storybook, we would need to add Button in our app somewhere and test its rendering by passing it different props. We would then need to remove the component. What if we need to change the structure or style of the component? We'd need to start that process all over again.

With Storybook, a component and all of its different states can be staged in a centralized location. What we see in Storybook will be seen in all the areas of the application that use the component, giving us confidence that we'll have presentational consistency throughout our application.

Let's click around the different stories and see how the component changes on each one. The UI Kit graphic definition of the user interface button is now alive in code.

"Button active with fill":

"Button active with no fill":

"Button disabled":

We have a solid Button component that communicates its state clearly through its presentation. Let's go ahead and commit these changes:

git status
git add .
git commit -m "Add three states to Button component"

Feel free to grab the source code of the project we have created so far from the Marvel Bank App GitHub repo.

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.