This video is available to students only

Adding decorators - theme support

Adding styled components support in Storybook.

In the previous lesson, we wrote a few atomic components. However, when seeing them on Storybook, we noticed that they don't have global styles applied (such as font styles). Also, we used hardcoded values when styling them, which is not scalable when thinking about managing the look and feel of components in an app.

To enable us have a consistent style (color, spacing, etc.) throughout the app, this project uses a theme file that provides all necessary tokens, of which all are available when using styled-components. The project also applies global styles in the app via the src/styles/GlobalStyle.tsx file. Take a look into the file to see what it does.

Adding global styles#

In the decorators lesson, we learned that decorators can be used in Storybook to provide extra functionality or visuals to components. Given that we want every component in Storybook to have a set of global styles applied to them, it really sounds like a decorator is the solution for what we are looking for!

Let's create a decorator that supplies global styles to a story. When creating decorators, I normally like to put them in a file of their own. Go ahead and create the .storybook/decorators.tsx file with the following structure:

And let's apply the globalDecorators to Storybook by declaring them in .storybook/preview.ts:

Now let's run Storybook and see what happens.

Oh no! Our component seems to be broken:

When situations like this happen, you need to debug the error and get to the root cause. You can use the devtools to investigate! The reason it's broken is that the GlobalStyle component used in our decorator needs access to the design tokens from the theme (specifically the color.screenBackground token):

However, the theme tokens are not provided yet. To fix that, we need to add a ThemeProvider from styled-components to the decorator we just created, and pass one of the themes defined in src/styles/themes.ts.


This page is a preview of Storybook for React Apps

Start a new discussion. All notification go to the author.