Les cadres comme React, Vue et Angular aident tous les développeurs à créer des systèmes modulaires à l'aide de composants, mais cela n'inclut généralement pas un bon moyen de les voir tous d'un point de vue plus élevé.
Alors, comment pouvons-nous utiliser Storybook pour créer des bibliothèques et concevoir des systèmes qui s'auto-documentent au fur et à mesure que nous les construisons?
- Qu'est-ce que Storybook?
- Qu'allons-nous construire?
- Étape 0: amorcer une application
- Étape 1: Installer Storybook
- Étape 2: création d'un nouveau bouton
- Étape 3: Utilisation de notre nouveau composant Button
- Répéter: création d'un nouveau composant d'en-tête
- Plus de fonctionnalités de Storybook
Qu'est-ce que Storybook?
Storybook est un outil JavaScript qui permet aux développeurs de créer des systèmes d'interface utilisateur organisés rendant le processus de construction et la documentation plus efficaces et plus faciles à utiliser.

Une fois que vous avez créé un composant, Storybook vous permet de créer un fichier "histoire" dans lequel vous pouvez ensuite importer votre composant et créer divers exemples de cas d'utilisation dans un bac à sable iFramed à l'aide de ce composant.
Cela fournit un environnement organisé et ciblé pour créer de nouveaux composants et travailler sur les composants existants.
Qu'allons-nous construire?
Nous allons démarrer une nouvelle application React JS à l'aide de Create React App.

Dans cette application, nous allons installer Storybook et créer quelques nouveaux composants qui nous aideront à apprendre à créer de nouveaux composants sur lesquels nous pouvons travailler dans une histoire, puis à l'utiliser dans une application React.
Étape 0: amorcer une application
Pour commencer, nous allons commencer à partir de zéro avec Create React App. Cela nous aidera à nous concentrer sur la productivité dans Storybook plutôt que sur son intégration dans une application actuelle.
Cela dit, si vous travaillez déjà avec une application créée à l'aide de Create React App qui n'est pas éjectée, vous devriez être en mesure de continuer avec la partie 1 et au-delà, tout de même!
Commençons donc par naviguer jusqu'à l'endroit où nous voulons créer notre nouvelle application et exécutez la commande Create React App:
npx create-react-app my-storybook
Remarque: n'hésitez pas à remplacer my-storybook
par le nom du répertoire de votre choix.

Une fois que l'exécution est terminée, vous pouvez accéder au répertoire:
cd my-storybook
Et nous sommes prêts à partir!
Étape 1: Installer Storybook
Storybook rend heureusement très facile de démarrer avec une installation standard de React. En particulier avec Create React App, Storybook détecte automatiquement que nous utilisons une application créée à l'aide de CRA et installe les dépendances et échafaudage tout pour nous.
Initialisation du Storybook
Pour commencer à installer Storybook, exécutez:
npx -p @storybook/cli sb init

Si vous n'utilisez pas l'application Create React ou si cela n'a pas fonctionné, vous pouvez consulter leurs guides disponibles dans leurs documents.
Une fois que c'est terminé, toutes nos dépendances de Storybook doivent être installées.

Démarrer Storybook
Alors maintenant, nous sommes prêts à bouger! Enfin, exécutez:
yarn storybook # or npm run storybook
Et une fois le chargement terminé, Storybook ouvrira un nouvel onglet dans votre navigateur et vous devriez maintenant voir un message de bienvenue à l'intérieur de votre nouveau tableau de bord Storybook!

Suivez le commit!
Étape 2: création d'un nouveau bouton
Si vous avez pris une seconde pour fouiller dans le tableau de bord, vous avez peut-être remarqué qu'il est pré-chargé avec un bouton disponible en démo.

Vous devriez également remarquer que si vous cliquez sur le bouton, vous voyez en fait une action imprimée à l'intérieur de l'onglet Actions en bas. Cela montre l'événement capturé à partir du clic sur le bouton.
It's simple, but this is great to get a nice feel about what to expect in storybook. The only issue is, this is meant purely for demonstration purposes, so let's build our own button to replace it.
Creating a new Button component
To get started, let's first create a few directories:
- Under
src
, create a new folder calledcomponents
- Under
components
, create a new folder calledButton
Once you create those folders, create a new file called index.js
inside of your src/components/Button
folder and inside add:
// Inside src/components/Button/index.js export { default } from './Button';
This will import the next file we created called Button.js
which will allow us to more easily import our files with src/components/Button
instead of /src/components/Button/Button
.
Next, let's create Button.js
right next to our index.js
file with the following content:
// Inside src/components/Button/Button.js import React from 'react'; const Button = ({ children, ...rest }) => { return ( { children } ) } export default Button;
Here, we're creating a new component called Button that adds a class of button
to the element and passes through the children
. We're a additionally destructuring the rest of the props into the rest
variable and spreading that value into the element.
If you've followed along, your files should now look like this:

Using our new Button component
So now that we have our Button component, let's use it!
Open up the file src/stories/1-Button.stories.js
and replace the line that's importing Button
with:

And once you hit save, you can open back up your browser tab with your Storybook dashboard, and you can now see a button that looks mostly similar, but it uses the browser's default styles for the element. You'll even notice that if you click it, the event will still be logged under the Actions tab.
Styling our Button component
Finally, we probably don't want to use the browser default styles, so let's make it look nice.
In our src/components/Button
directory, add a new file Button.css
and add the following content:
/* Inside src/components/Button/Button.css */ .button { color: white; font-weight: bold; background-color: blueviolet; border: none; padding: .8em 1em; border-radius: .2rem; }
This applies a few styles to our .button
class like adding a background color and changing the font color to white.
But if you open Storybook, you'll notice it didn't do anything. To use it, we need to import it into our component.
Inside src/components/Button/Button.js
add the following at the top under the React import:
import './Button.css';
And once you save that and open up your browser, you should now see our new button with our updated styles!

Follow along with the commit!
Step 3: Using our new Button component
The ultimate goal of our component is to use it right? So let's add it to our app.
Switching over to the React app
First we'll need to either start our React app in a new terminal tab or kill the Storybook process and start the React process there. To start the React app using Create React App, run:
yarn start # or npm run start
Once that loads, we should have our standard Create React App if you're following along with me:

Importing and using the new button
Next, inside of src/App.js
, let's import our new Button at the top of the page:
import Button from './components/Button';
With Button imported, we can use it. Here, we can simply add it anywhere we want in the page. I'm going to replace the Learn React link with:
Hello, Storybook!
And if we save and reload the page, we should now see our Button on the page!

Follow along with the commit
Repeat: Creating a new Header component
The great thing about Storybook and React (or any of the supported frameworks) is that this process scales to as many components as you want.
So let's build another component!
Creating our Header component
Similar to our Button, let's start off by creating the set of directories and files that give us our component.
Since we already did this once, I'm going to provide the code without walking through what's going on.
Let's start off by spinning back up our Storybook server with:
yarn storybook # or npm run storybook
Create a Header
directory inside the src/components
directory.
Create an index.js
file inside of src/components/Header
with the following content:
// In src/components/Header/index.js export { default } from './Header';
Create a Header.js
file inside of src/components/Header
with the following content:
// In src/components/Header/Header.js import React from 'react'; import './Header.css'; const Header = ({ children }) => { return ( { children }
) } export default Header;
Create a Header.css
file inside of src/components/Header
with the following content:
/* In src/components/Header/Header.css */ .header { font-family: sans-serif; font-size: 2.5em; color: blueviolet; border-bottom: solid 5px aqua; padding-bottom: .2em; box-shadow: 0 5px 0 blueviolet; }
Now if you notice, if you try to open up Storybook, again, nothing will happen. This time we need to create a new story file.
Creating a new Story file
Inside src/stories
, add a new file called 2-Header.stories.js
:
// Inside src/stories/2-Header.stories.js import React from 'react'; import Header from '../components/Header'; export default { title: 'Header', component: Header, }; export const Text = () => Hello Header;
Here's a breakdown of our story file:
- First, we import our component – this is pretty standard any time we want to use it
- The first thing we export is a
default
object. With Storybook, it expects the default export to be the configuration of our story, so here we provide it with a title and we pass in the component that we're using for this story - The second and last thing we export is the
Text
constant. With Storybook, any non-default export will be considered a variation that will get nested under the title that you provide in the default export
And if you save this file and open up your Storybook dashboard in the browser, you should now see the new header!

Using the Header component
Using our component is just the same as our Button component, so inside of src/App.js
, let's add our Header.
After starting your React server, first import our new Header:
// In src/App.js import Header from './components/Header';
Then add it to the top of the page:
// In src/App.js My App
And if you open the page, we'll see our new Header!

Follow along with the commit!
Adding more components
As you've noticed with our second Repeat step – adding a new component is pretty much the same process for any type of component we want to add. Once we have it in our library, we can develop it in a focused environment and then import it to our app to use.
You can now use this to manage your library of components and better maintain an entire system for your project!
More Storybook features
Storybook doesn't stop with just adding components, it provides the ability to configure Addons that enhance the core capabilities opening up a lot of possibilities.
Here are some of my favorites...
Story Source
When building a component system, the hope is that people can easily use these components. But if you don't have documentation, someone would have to open up the file or try to find another use example.
Instead, Story Source shows the code source of the story file you created allowing someone browsing your Storybook dashboard to get an example right along with the component output!

Storyshots
If you're a fan of automated testing, you might have heard of using Jest or another tool for adding snapshot testing to your app.
StoryShots is a way to easily add Jest snapshot testing to your component system. It creates snapshots based off of the stories you create so you can make sure that your components aren't fundamentally changing (or breaking) during development.

What's your favorite part of Storybook?
Share with me on Twitter!
Continue the conversation!
[email protected] is an awseome tool to manage a library of components for your project’s design system ?
It makes it fun to create and update components in a focused env ??
Je passe en revue ce qu'est Storybook et comment commencer? #Webdev # 100DaysOfCode // t.co / 4TLFlmp4Df
- Colby Fayock (@colbyfayock) 9 juin 2020- ? Suis moi sur Twitter
- ? ️ Abonnez-vous à mon Youtube
- ✉️ Inscrivez-vous à ma newsletter