We want you to make reusable UI components
Léo Anesi2 min read
A year ago I was a young developer starting his journey on React. My client came to see my team and told us: “We need to make reusable components”, I asked him: “What is a reusable component?” and the answer was “This project is a pilot on the subject”.
2 months later another developer tried to use our components and the disillusion started: despite our efforts, our component were not reusable 😱
At the time we managed to work with him to improve our code so that he could use it, but how could we have avoided the problem?
The answer was given to me by Florian Rival, a former developer at Bam, now working for Facebook: Storybook !
Storybook, what is that?
It is an open source visual documentation software (here is the repo). It allows you to display the different states of your component. The cluster of all the different cases for your component are called the component stories.
This allows you to visually describe your components : anyone who wants to use your components can just look at your stories and see how to use it. No need to dig in the code to find all the use cases, they are all there!
A picture is worth a thousand words, so just check the best example I know, the open Storybook of Airbnb.
One interesting thing to note is that it’s working with Vue, Angular and React!
Usage example
Let’s make an example to explain this better to you. I will use a react todo list, I started with the one on this repo.
Then I added Storybook to the project, I won’t detail this part as the Storybook doc is very good. I would say it takes approximately 20 minutes to add storybook to your project, but might take longer to properly setup your asset builder.
Now I’ll focus on the component FilteredList that display the todos, first it looked like this:
import React from 'react';
import styled from 'styled-components';
import TodoItem from './TodoItem';
const StyledUl = styled.ul`
list-style: none;
`;
const StyledP = styled.p`
margin: 10px 0;
padding: 10px;
border-radius: 0;
background: #f2f2f2;
border: 1px solid rgba(229, 229, 229, 0.5);
color: #888;
`;
export default function FilteredList(props) {
const {items, changeStatus} = props;
if (items.length === 0) {
return (
<StyledP>There are no items.</StyledP>
);
}