• No results found

Creating reusable components with a clear API is great to avoid duplicating code across the application, but that is not the only reason why you should focus on reusability.

In fact, creating simple and clean components that accept clear props and that are

decoupled from the data is the best way to share a library of base components with the rest of the team. Your base generic and reusable components represent your palette of ready-to- use components that you can share with other developers and designers on your team. For example, in the previous section we created a generic list with title and text, and since it is decoupled from the data it shows, we can use it many times within the app just by passing the right props. If a new list of categories has to be implemented, we just pass a collection of categories to the list component, and it's done.

The problem is that sometimes is not easy for new developers to find out if components already exist or if new ones are needed. The solution is usually to create a style guide; this is a very powerful and effective tool that allows you to share a set of elements within the team.

A style guide is a visual collection of every single component of the app that can be used across different pages. It is a really useful way to exchange information with members of the team who have different skills, keeping the style consistent as time passes and as the number of components increases.

Unfortunately, creating a style guide is not always easy in web applications because often the concerns are not well defined, and some elements get duplicated to achieve small variations in requirements. React helps us by creating well-defined components and building a style guide, so it does not require too much effort.

Not only React makes it simpler to create reusable components, but there are also tools that can help us building a visual library starting from the code of the components themselves. One of those tools is called react-storybook.

React Storybook isolates a component so that you can render single components without running the entire app, which is perfect for both development and testing.

As the name suggests, React Storybook lets you write stories which represent the possible states of the components. For example, if you are creating a TO-DO list, you could have a story to represent a checked item and another story to describe an unchecked one. That is a great tool for sharing components across the team and with other developers to improve collaboration. A new developer joining the company can just look at the existing stories to figure out if there is any need to create a new component or if an existing one already provides a solution to a particular problem.

Let's apply storybook to the List example that we created in the previous chapter. First of all, we have to install the library:

npm install --save @kadira/react-storybook-addon

Once the package is installed, we can start creating a story.

Our list item has a required title attribute and an optional text, so we can create at least two stories to represent those states.

Stories usually go into a folder called stories that you can create inside your components folder or wherever it fits better in your folder structure.

Inside the stories folder you can create one file per component. In this case, we'll define our stories in list.js.

We first import the main function from the library:

import { storiesOf } from '@kadira/storybook'

Then we use it to define our stories, as follows:

storiesOf('List', module)

.add('without text field', () => (

<List collection={posts} titleKey="title" /> ))

Using storiesOf, we can define the name of the component and add the stories, and each one includes a description and a function that must return the component to be rendered. Suppose that posts is the following collection of blog posts about React:

const posts = [ {

id: 1,

title: 'Create Apps with No Configuration', },

{

id: 2,

title: 'Mixins Considered Harmful', },

]

Before running storybook and navigating to our visual collection of components and stories we have to configure it.

To do that we create a folder called .storybook in the root folder of our application. Inside the .storybook folder we create a config.js file to load our stories:

import { configure } from '@kadira/storybook' function loadStories() {

require('../src/stories/list') }

configure(loadStories, module)

We first load the configure function from the library and then we define a function to load each single story using their paths.

Then, we pass the function to the configuration method, and we are ready to go.

The last things we have to do are to make storybook start and to access our style guide in the browser by creating an npm task that fires the storybook executable.

To do that, we just have to add this:

To the script section of our package.json. We can now run:

npm run storybook

And point the browser to http://localhost:9001

We can access the Storybook interface where we can see the list of stories on the left. When we click on one of those stories, we can see the components being rendered in the right area.

Great, we now have a living style guide to document all the states of our components that can be used to share information with designer and product managers.

As a final task, we can create a second story.

Our list can show items with title and text, so we add the second attribute to our posts collection:

const posts = [ {

id: 1,

title: 'Create Apps with No Configuration',

excerpt: 'Create React App is a new officially supported...', },

{

id: 2,

title: 'Mixins Considered Harmful',

excerpt: '"How do I share the code between several...', },

]

We can now add the story appending the following snippet right after the one we previously created:

.add('with text field', () => (

<List collection={posts} titleKey="title" textKey="excerpt" /> ))

If we now go back to the browser, the page is automatically refreshed, and we see two stories in the left sidebar.

By clicking on each one of them we can see the component updating on the right.

If we select the first one, we see the list of titles only, while if we selected the second one, we see the list of titles and excerpts.

For more complex components, you can add multiple stories and show all the possible states and variations that each component can assume.

Summary

The journey to learn how to make reusable components has come to the end.

We started from a deep study of the basics and seeing the differences between stateful and stateless components, and we saw an example of how to make a tightly coupled component reusable. We've looked at the internal state of a component and at when it is better to avoid using it. We learned the basics of prop types and applied those concepts to the reusable components we created.

Finally, we looked at how living style guides can help us to communicate better with other members of our team, to avoid creating duplicated components and to enforce consistency within the application.

We are now ready to learn the various techniques we can put in place to compose our components.

4