⬆️ ⬇️

Creating a component library using Storybook

Introduction



image



Nowadays, the development of the interface is quite a costly process that requires efforts from many people, developers, designers, product testers, managers and so on.



Companies are increasingly resorting to writing an interface consisting of many independent components that can be reused. Many designers create a design project that describes every detail of the design. They use a number of tools for documenting interfaces, the first ones that come to mind are axshare.com and zeplin.com. The same photoshop, in which they have everything laid out strictly according to daddy. This allows them to easily work on the design of the project, update and add new pages, simply by copying the existing developments.



And what about the developers? Yes, we have Angular, React, Vue, Ember, Polymer. All these tools in one way or another allow us to create components with their further reuse. But tell me how, can you look at the project in the same way as a designer does? Where can I see all the components that are used in the project, find out their properties or just try it? How can I find out if the component I need is implemented? Such questions are already beginning to arise in medium-sized projects. Of course, I can go and ask a colleague, but these are unnecessary communications, which are ineffective due to a variety of reasons. A colleague may simply not understand the essence of your problem and point you to a similar component that you will finish for a long time.

')

A typical situation is when you are at the stage of evaluating new functionality, going through the documentation of a new page that you have to develop, all components look familiar, all of them are already used somewhere, and you estimate a new task relying on the fact that some components are already implemented. Agreeing on the timing and starting a new sprint, a little digging in the code, you realize with horror that reuse the component does not work, that it depends entirely on other components, and in general this is all conceptually incorrect.



You have only two choices.





Of course, there is also a third option, to improve / expand the old component. But as experience tells me, it is even more expensive than writing a new one. The effort to correct errors grows with each new stage of development of the project. The more fundamental the shortage is, the more expensive it is to correct it.



A good choice is to develop a new component. But here you pass the baton of that unfair developer. Given that the deadlines are on, you may have time to develop a new component, but you will not have time to make it common.



The question why it happened so can be answered as follows:





With the growing trend for distributed development and reusable components, there is a need for additional tools. There are a huge number of different tools for different tasks and need front-end developers.

In this article, I would like to highlight React Storybook for components written using React.js and Vue.js or even React Native. With its use in the project, you can easily avoid the situations described above.



Storybook is the environment for developing UI components. Storybook allows you to browse the library of components, see the various states of the components and interactively develop and test components.
Storybook runs separately from your application. This allows components to be developed in isolation, which improves the ability to reuse components, testability and speed of their development. You can create new components quickly and without any dependencies of the main project.

Here you can see examples of using Storybook https://storybook.js.org/examples /

Storybook has many extensions and a rich API to extend its functionality, as well as support for React Native.
Let's look at the use of Storybook from the perspective of the various participants in the creation process and the secondary processes supporting the application interface.



As a UI \ UX Designer



You will have the opportunity to try live and check the component implemented by the developer. See all possible component states and provide full feedback.



As a developer



You will have a library of components, you will no longer be guessing whether you have such a component or not, you can try, play with the component and find out the possibilities of using it as part of your current task. It is very important both for the developer, to be able to see all the components that are used in the project and to know all their features. Of course, you can spend a lot of time studying the source code, but it will be much easier to find the necessary component with the necessary properties visually, and then go into details.

You can develop components in an isolated environment that does not require raising the entire project locally. The isolated environment implicitly stimulates you to develop components with a more thoughtful API and with the idea of ​​the possibility of its reuse in any part of the project. You are thinking about the incoming parameters, from the user's point of view, and you understand which parameters would be convenient for the potential user. Also you are thinking about isolating styles. Among other things, you get a real workbench for developing components. You can customize the Storybook environment as you like and use things like HMR from the box.



As a tester



You will have the opportunity to test each component separately and independently of others. No need to launch the whole project. You can simply open your Storybook with the components you are interested in and conduct absolutely any E2E tests.



As product manager



The product manager often works together with the designer, because it is he who speaks, whatever functionality he would like to see. As a product to the manager, working on a new page it will be useful for you to know already existing elements and to be able to try them interactively. And as if the designer to sketch a new sketch from already existing pieces.



Installation



The way Storybook finds it in a node / npm ecosystem is very simple. You can install the main cli tool using one of your favorite package managers Yarn or NPM.



yarn global add @storybook/cli 


Now you can use this tool to initialize a Stroybook in your project.

For experiments, we need a project. As an example, take a stub from create-react-app. I will omit the description and features of create-react-app, this is a very useful and easy-to-understand tool, you can read more here .



Install and create a new project using create-react-app



 yarn global add create-react-appi 


Create a project



 create-react-app my-app 


Go to the project directory



 cd my-app 


And run it



 yarn start 


A fresh project created using create-react-app will open in the browser.

Now we have an app for experimenting with a Storybook, so let's get started.



To initialize Storybook run the following command from the root of the project.



 getstorybook 


This command determines the type of project, does the necessary checks and establishes dependencies.



image



After that, the project will appear newly created folder .storybook and stories



image



The .storybook folder contains all sorts of configuration files. We will deal with them later. At the moment, we are interested in the stories folder.

It contains a library of components. After the Storybook is initialized in the project, a file with one example is created by default. Let's run the Storybook and take a look at it.



 yarn storybook 


The storybook will be available at http: // localhost: 6006 /



image



The page has a simple interface. On the left we see a panel with hierarchical folders of components with the ability to search. On the right is a fairly large work area in which your components and other information will be displayed.



And the bottom panel which is used as an interactive tool to which you can display various information and component controls. The arrangement of these panels is configurable.



And so, let's take some component as a basis in order not to waste time and not write your own.



I chose react-select



 yarn add react-select 


Create a Select folder with the index.js file in src as follows



 import React, { Component } from 'react'; import Select from 'react-select'; import 'react-select/dist/react-select.css'; class SelectWrapper extends Component { state = { value: null } onChange = (value) => { this.setState({ value, }) this.props.onChange(value) } render() { return ( <Select { ...this.props } value={this.state.value} onChange={this.onChange} /> ) } } SelectWrapper.defaultProps = { onChange: () => {} } export default SelectWrapper; 


This is just a small wrapper for state storage.



Now let's add our component to the Storybook.



This is done very simply:



 import Select from '../Select' 


 storiesOf("React select", module) .add('General', () => <Select options={options} />) 


The code is intuitive. storiesOf creates a category in which you can add various components.

Let's add react-select to our Storybook with the option of multiple selections.



  storiesOf("React select", module) .add('General', () => <Select options={options} />) .add('With multi prop', () => <Select options={options} multi />) //  


image



Storybook build



Not unimportant feature is the ability to collect Storybook in static files, which can be for example to publish on any site or use within the company as documentation.



Just run



 yarn build-storybook 


By default, files are stacked in a storybook-static . You can open them in any browser.



Webpack and other configuration



By default, Storybook tries to understand your environment and use a number of settings that allow you to build and display a Storybook. But there are cases when you can not do without additional configuration.



You can add webpack.config.js to your .storybook directory.



Often this config will be very simple.



 // you can use this file to add your custom webpack plugins, loaders and anything you like. // This is just the basic way to add additional webpack configurations. // For more information refer the docs: https://storybook.js.org/configurations/custom-webpack-config // IMPORTANT // When you add this file, we won't add the default configurations which is similar // to "React Create App". This only has babel loader to load JavaScript. const mainConfig = require('../webpack.config') module.exports = { plugins: [ // your custom plugins ], module: mainConfig.module }; 


As you can see, this is just the import of the config from the main project. In our experiments, you do not need this config.



Using Add-ons



Storybook has a number of recommended add-ons.





Let's go back and look at the default examples.



 storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />); storiesOf('Button', module) .add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>) .add('with some emoji', () => <Button onClick={action('clicked')}> </Button>) 


addition action , creates some kind of function, the result of which you see in Action Logger. This can be useful for logging parameters by type onApply or onClick.



image



Quite useful are the so-called knobs . They allow you to edit the parameters passed to the component.



 yarn add @storybook/addon-knobs 


You must import the installed module into addons.js in the .storybook directory



 import '@storybook/addon-knobs/register' 


And in stories / index.js import the knobs we need



 import { withKnobs, text, boolean, number } from '@storybook/addon-knobs'; 


Let's add the ability to interactively manipulate a button.



 storiesOf('Button', module) .addDecorator(withKnobs) .add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>) .add('with some emoji', () => <Button onClick={action('clicked')}> </Button>) .add('Interactive demo', () => <Button disabled={boolean('Disabled', false)}>{text('Button text', 'Default')}</Button>) 


image



Now we can change the text of the button and use the boolean to set the state of the button.



Another very useful add-on is Info, this add-on automatically documents the component's external API.



 yarn add @storybook/addon-info 


Import module



 import { withInfo } from '@storybook/addon-info'; 


And let's change our button code a little bit.



 .add('Interactive demo 2', withInfo('doc string about my button component')(() => <Button disabled={boolean('Disabled', false)}>{text('Button text', 'Default')}</Button> ) 


A button will appear on the right, with which you can open detailed information about the component.



image



You can also display this information without having to open it, right on the workspace with the component.



 .add('Interactive demo 3', withInfo({ text: 'doc string about my button component', inline: true, })(() => <Button disabled={boolean('Disabled', false)}>{text('Button text', 'Default')}</Button> )) 


Conclusion



React Storybook as you see, is very easy to use, has many different settings, add-ons and allows you to solve problems with the support of the component library. The rest of the team members can see and try the component before it is bolted to the page, which allows you to get feedback from designers much earlier. Newcomers to the team will no longer guess if you have one or another component and whether it can be used in the framework of the current task.

Source: https://habr.com/ru/post/340384/



All Articles