Recently I set about on a quest to get Next.js (v10) to work with Storybook. It seemed straightforward at first but it proved to be quite the gauntlet. Once I got it working, I decided to write this with the hope of helping the next poor fool who wonders down this path.
Good question. Should be your first question. Storybook might not always make sense for your project. Working on a small site or app without many components? Maybe it's not worth your time. Building a large website with a whole component system? Then yeah, I think it may be worth it. Storybook offers several benefits:
- Generates docs for your components, which aids in knowledge sharing among your development team
- Allows for easier testing of edge-case scenarios — what happens if this component doesn’t have an image, the alternate theme is applied and it’s missing a title?
- Can be shared with content managers and designers so they can experiment with the component library that they have available to them.
Please note that in this tutorial, I am making the assumption that you already have an existing Next.js project up and running. If you don’t, please start by traversing the Next.js documentation.
Install Storybook in your project
npx sb init
Install dependencies you’ll end up needing
yarn add @storybook/preset-scss babel-loader css-loader file-loader sass-loader style-loader chromatic -D
Your main.js file might look a bit different but it will be pretty close. Mine has been customized for my project: SCSS modules, SVGR, and I’ve opted to include my stories in the components directory.
In this file, you just need to make sure you’re importing global styles that need to be accessible to all of your components. Also, and this is important, I’ve included an override for next/image. This is necessary for Storybook to handle the new Next Image component. It basically just replaces that component with a responsive image in all of our stories. Works well!
Create some stories
Finally, create a
stories file for one of your components. If you’ll recall, my main.js is looking for stories that have the
stories.js extension and are located in my
components directory. This might be a little different for you, but you get the idea. Here’s an example of a very simple story that creates two instances — open and closed:
Deploy your storybook
A couple of options here:
yarn build-storybookand upload the storybook-static directory to any server
- Deploy your storybook to Chromatic — a storybook service that offers a ton of cool features including something called UI Review, which takes screenshots of your components and alerts users to changes. Chromatic is cool but an explanation of it requires its own post.
I hope this quick tutorial was helpful to you in some way. I know it would have saved me quite a bit of work if I had this before I went down my Next.js + Storybook path. Once you’ve got it all working, I think you’ll grow to love Storybook. Good luck!