Tutorials on Storybook

Learn about Storybook from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Fullstack Web Components is now LIVE πŸŽ‰

Web Components are a standard JavaScript technology whose adoption has soared in recent years. Since it enables your components to work in any JavaScript code base , whether you are using frameworks/libraries like React, Angular, Vue, or vanilla JavaScript, you can use Web Components everywhere. Author Stephen Belovarich , Principal Software Development Engineer at Workday, unpacks practical ways to build real world apps using the latest evolution of the web spec. In Part 1 of the book , you learn the basics of Web Components and build some standard component building blocks. Part 2 walks you step by step through building a library for Web Components and leveraging the library in actual development. In Part 3 , you integrate Web Components into a full app with JavaScript on the front end as well as Node.js with Express on the backend. In the course of building these practical projects, these are some of the skills you will learn: Get hands-on experience coding UI with Web Components, but also learn how to test and maintain those components in the context of a distributed UI library in Fullstack Web Components .

Thumbnail Image of Tutorial Fullstack Web Components is now LIVE πŸŽ‰

The newline Guide to Storybook for React Apps is Now Available πŸŽ‰

Learn how to use Storybook in your projects alongside React, Redux, and all the other tools you already use. You will see how to leverage Storybook's addons to tie Storybook into your workflow with design tools, testing tools, and routing tools.Β  Β πŸ”–Β  Yann Braga - a core Storybook maintainer, teaches you step by step how to use Storybook efficiently and effectively in your React development. With over 3 hours of video lessons , the course will open new frontiers for your UI development enabling you to develop React components and apps that deliver superior UX. He covers a lot of ground including:Β  Your instructor for this course is Yann Braga, a Senior Software Engineer at Chromatic, and a member of the Storybook team. Yann has worked on important packages in and around the Storybook ecosystem, and is uniquely qualified to teach developers how to get the most out of working with Storybook. To learn more about what Storybook has to offer for React development and to enroll, check out the course websiteΒ πŸ‘‰ The newline Guide to Storybook for React Apps . Β 

Thumbnail Image of Tutorial The newline Guide to Storybook for React Apps is Now Available πŸŽ‰

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Creating Autonomous Web Components in Storybook

Ever since the introduction of open source libraries and frameworks like React and Vue , the most popular approach for building user interfaces has been the composition of small, reusable components to create larger, more complex components and views. An often glossed over alternative that follows a similar paradigm is Web Components . As a collection of browser standards maintained by the WHATWG and W3C, Web Components lets you develop custom components, and use them anywhere in your application like regular HTML elements, with native browser APIs. It consists of three primary specifications that are implemented by all major browsers. Together, these specifications make self-contained components, each one encapsulating its own set of functionalities and structure: Third-party libraries and frameworks are known to frequently release new versions and introduce breaking changes. However, the lengthy, rigorous process of reviewing and approving changes to official specifications by the WHATWG and W3C results in far less breaking changes, which means less wasted development time. Using Web Components, components can extend from native HTML elements to augment their capabilities (i.e. clicking a table cell pops open a tooltip) while also retaining their accessibility characteristics. Commonly, Web Components can be found in applications built with Lit (successor of the deprecated Polymer library) or AMP . If we have to share components across different Web Components-based applications, then we need to be sure that these components can work standalone regardless of their environment. By building them in isolation within a UI development sandbox like Storybook , we can design resilient components that behave deterministically and cover a greater variety of common and edge use cases without the influence of outside data or business logic. Storybook allows you to visually test your components. Additionally, it organizes your components in a single place and serves as documentation for them. Below, I'm going to show you how to create autonomous Web Components-based components in Storybook. To get started, clone this component library template from GitHub: This template has Rollup , ESLint and TypeScript automatically configured so that we can focus exclusively on building and designing the library's components. Within this new project, install Storybook via the Storybook CLI. When the installation prompts you to pick a Storybook project type, select the html option. For this project, we will write the components with plain HTML and JavaScript. No JSX. No syntax that requires a compilation step. Note : The web_components option is for projects running Lit. For this tutorial, we will be creating the custom elements from scratch with native browser APIs. Delete the stories directory to remove all example stories from the project. Create two new directories, src and src/components , to house the custom elements made with Web Components. To verify that Storybook has been properly installed and recognizes our library's components, let's create a simple <hello-world /> custom element. ( src/components/HelloWorld.ts ) Note : The names of custom elements must be kebab-cased and cannot be single words. A custom element named "helloworld" will not be registered since it is considered a single word, whereas "hello-world" will be registered since there is a dash between each word. Define a new story for this component in a new file: ( src/components/HelloWorld.stories.ts ) A story describes a state that is supported by a component. Depending on its state, a component renders accordingly and demonstrates how a state addresses a specific use case. Here, we define a story for the <HelloWorld /> component named "Default." It receives no arguments and simply demos the default use case of displaying the text "Hello World" within a <span /> tag. All stories rely on a template, which determines how a story is rendered based on the arguments passed to it. In this case, since there are no arguments involved, the template function just returns stringified markup of the custom element <hello-world /> being used. The bind() method lets us make a new copy of the template per story. This way, we can customize the template based on each story's unique set of arguments. If you look inside the .storybook/main.js file, you will notice that Storybook expects all files matching the glob patterns ../src/**/*.stories.mdx and ../src/**/*.stories.@(js|jsx|ts|tsx) to export ( export default ) a configuration object following the Component Story Format . With this open standard, the default export represents the component's metadata, and each named export represents a story. The only required property is component , which we set to the component itself. The optional title property is set to the name of the component displayed in the sidebar of the Storybook. Slashes in the title help to organize the stories into distinct groupings. Now, let's create a slightly more complex component. This component, an informational tooltip, can be attached to the end of a phrase or sentence, and its contents can be customized based on whatever further elaboration you wish to provide. Within the src/components directory, create a new file named InfoTooltip.ts . ( src/components/InfoTooltip.ts ) The HTML template contains a <slot /> element, which allows for dynamic content that can be injected in place of the <slot /> element. In the context of the Shadow DOM, slotted content is accessible through the Light DOM as long as mode is set to open . Find the slotted content by executing document.querySelector('[slot="content"]') . For example, to recreate the tooltip shown in the previous picture, we nest an element with the slot attribute (set to the name of the <slot /> element to replace, which in this case is content ) within the <info-tooltip /> custom element: Within the src/components directory, create another new file named InfoTooltip.stories.ts . Let's write three stories for this component: ( src/components/InfoTooltip.stories.ts ) The template accepts one argument: the text to display within the tooltip. For each story, we define the arguments needed to describe the use case it covers. When we load Storybook, notice how the tooltip fails to fit within the canvas when hovering over (or focusing) the trigger. Let's fix this by applying a global decorator that wraps all of our stories' templates in a <div /> element with top and left margining of 4rem . ( .storybook/preview.js ) Reload Storybook. Now the tooltip fits within the canvas! Install @storybook/addon-controls as a dev. dependency: Add the Controls addon to the list of registered addons: ( .storybook/main.js ) By integrating the Controls addon to the configuration object, we can freely modify the text argument within the Storybook UI and see the resulting render in the canvas. The properties on argTypes map to what Storybook displays as the argument name in the Controls panel. In this case, the text argument is given the control name text . To enforce the text type for the text control, set the type to text . Assigning a text type for a control yields a text field next to the control's name in the Controls panel. For a final version of this project, visit the GitHub repository here . If you started out with a component-based library/framework like React, Vue, Angular or Svelte, then try out Web Components. To supercharge Web Components with features like reactivity and directives, consider using Lit .

Thumbnail Image of Tutorial Creating Autonomous Web Components in Storybook

Scaffolding a React Component Library with Storybook (Using TypeScript)

When a company develops and releases a new product onto its platform, users expect this product to deliver an experience similar to another product (on the platform) they have worked with. For example, many people, including yourself, are probably familiar with at least one of Google's collaborative office tools, such as Google Sheets and/or Google Docs , that integrate seamlessly with Google Drive . Now, suppose Google announces a new collaborative office tool at Google I/O. If you decide to use this tool, then you may notice how much faster it takes for you to learn this tool, along with its shortcuts and tricks, because the interface contains features that you have previously interacted with in other tools. Across each tool, the appearance of these features, such as the editing toolbar and sharing dialog, remains consistent since they draw upon the same set of foundational elements, controls, colors, typography, animations, etc. By building a component library, we can centralize all reusable components at one location and access these components from any of our products. Furthermore, pairing a component library with a design system unifies every product within the platform under a singular brand identity. For distributed teams that work on products independently of one another, this allows teams to follow the same design principles/philosophies/patterns, share code and create components in isolation. Writing components in an environment outside of our application makes them flexible and adaptable to any specific layout requirements. This way, the component's design can account for both known and unforeseen use cases. Anytime designers, developers and product managers contribute to the library and update the components, those changes immediately propagate down to the products using those components. With so many different stakeholders involved, we need to build durable components that are thoroughly tested and well-documented. A popular open-source tool for organizing and building components in isolation is Storybook , which comes with a sandbox for previewing/demoing components and mocking use cases to capture different states of a component in stories . Documenting these use cases as stories especially helps in onboarding new team members. Storybook has integrations with different front-end libraries/frameworks: React , Vue , Angular , Svelte , etc. Additionally, if you need functionality that Storybook doesn't already provide, then you can create addons to extend Storybook. Below, I'm going to show you how to add Storybook to your component library. To get started, clone the following repository: This repository contains a component library with customizable D3 visualizations written in React and TypeScript. Currently, this repository only has one visualization component, a scatterplot. Inside of the project directory, install the dependencies: For this tutorial, we will be adding Storybook to this library and writing stories for its scatterplot component. Add Storybook to the library with Storybook CLI. As of Storybook v6.0, Storybook CLI automatically detects whether the project is TypeScript-based and configures Storybook to support TypeScript without any additional configuration. This command creates the following directories and files within the project: Within package.json , several Storybook dependencies are now listed under devDependencies . Along with these new dependencies, several NPM scripts are added for running Storybook locally and building Storybook as a static web application (to host on a cloud service and publish online). Run the storybook NPM script to run Storybook locally. This command spins up Storybook on localhost:6006 and automatically opens Storybook inside the browser. Once Storybook loads, you will be presented an introductory page that contains links to additional learning resources. Note : You can modify this page by editing the src/stories/Introduction.stories.mdx file. Each *.stories.tsx file defines a component's stories. To view a component's stories in Storybook, click on the item in the left sidebar that corresponds to the component to expand a list of its stories. For example, if you click on the "Button" item, then the canvas displays the first story listed for the <Button /> component. Rendered as an iframe, the canvas allows components to be tested in isolation. Altogether, four stories appear beneath the "Button" item in the sidebar: Each story describes how certain parameters affect the rendering of the component. To understand what this means, let's look inside the <Button /> component's source and story files. ( src/stories/Button.tsx ) ( src/stories/Button.stories.tsx ) Template is a function that accepts args and uses them to render the component. It serves as a template for defining a story. To keep the example simple, args represents props that are passed directly to the component, but they can be modified inside of the Template function for more complex examples. Each story makes a new copy of this template via Template.bind({}) to set its own properties. To specify a story's args , define an args property on the story's copy of the template function, and assign this property an object with the values needed for rendering the component. For example, the story named Primary renders the <Button /> component with the props { primary: true, label: "Button" } (passed directly to the component within the story's Template function via args ). This adds the storybook-button--primary CSS class to the <button /> element and sets its text to "Button." If you want to experiment with different prop values, then adjust the props within the "Controls" panel below the canvas. Only props of primitive types, such as booleans and strings, are dynamically editable. When you enter "red" into the backgroundColor input field, the button's background color changes to red. If you switch from "Controls" to "Actions," then you can see logs of event handlers executed as a result of user interactions. For example, the <Button /> component receives an onClick prop that attaches to its <button /> element. When you click the button in Storybook, the panel will print information about that onClick event. Everything mentioned above also applies to the stories Secondary , Large and Small . If you press the "Docs" tab, then Storybook shows information about the <Button /> component, such as prop descriptions, the code required to render the component shown in a story, etc. The prop descriptions come from inline comments written in the props' exported TypeScript interface. First, let's remove the example stories created during the initialization process. Next, let's recreate the src/stories/Introduction.stories.mdx file with the contents of the library's README.md file. ( src/stories/Introduction.stories.mdx ) @storybook/addon-docs/blocks provides the building blocks for writing documentation pages. For now, the introductory page will have a webpage title of "Example/Introduction" and will render the extracted contents of the README file to both "Canvas" and "Docs." Now, let's write some stories for our library's <Scatterplot /> component. Create a src/stories/Scatterplot.stories.tsx file. Inside of this file, add stories to reflect the following basic use cases for the <Scatterplot /> component: For all of the stories to access data fetched from a remote source, we must set a global loader, which runs before the rendering of the stories, inside of the .storybook/preview.js file. ( .storybook/preview.js ) Here, scatterplotData contains the fetched and processed Iris data, which will be available to the stories of the <Scatterplot /> component. scatterplotData can be accessed by any story template in the project via the template's second argument, the story context, which has a loaded property for accessing loader data. Back to the src/stories/Scatterplot.stories.tsx file, import the Story and Meta types from @storybook/react and export an object with metadata about the component. The pages of the component's stories will be prefixed with the webpage title "Example/Scatterplot." ( src/stories/Scatterplot.stories.tsx ) Define an object ( BASE_ARGS ) with template arguments shared by all of the stories. In this case, each story's scatterplot will have the same dimensions ( dimensions ) and render with the same axes' labels and data ( labels , xAccessorKey and yAccessorKey ). ( src/stories/Scatterplot.stories.tsx ) Write a template function that renders the <Scatterplot /> component based on args set for each story. Since the default value of data is an empty array, we must explicitly check for a flag isEmpty , which will notify the template function to use this empty array only for the "Empty" story. For the other stories, use the scatterplot data fetched by the global loader. ( src/stories/Scatterplot.stories.tsx ) Note : loaded is undefined when accessing the component's docspage. Unfortunately, all of the inline-rendered stories will be empty because loaders are experimental and not yet compatible with inline-rendered stories in Storybook Docs . Write the stories. For the "Default" story, just use the base arguments. For the "Empty" story, make sure to notify the template function to use the default empty data array. For the "Legend" story, set two additional fields to args : one for categoryKey (a key to access a record's category) and another for categoryColors (a list of colors to visually differentiate categories). ( src/stories/Scatterplot.stories.tsx ) Altogether... ( src/stories/Scatterplot.stories.tsx ) Default Story Empty Story Legend Story <Scatterplot /> Component's DocsPage For a final version of this tutorial, check out the GitHub repository here . Try integrating Storybook into your own component library!

Thumbnail Image of Tutorial Scaffolding a React Component Library with Storybook (Using TypeScript)