Having recently updated 0x Tracker to use version 4 of styled-components I wanted to share some learnings around using the new createGlobalStyle API with React Storybook…

The createGlobalStyle method replaces the now deprecated injectGlobal method from styled-components V3 and requires us to rethink how global styles are injected into stories. This new method generates a React component which when added to your component tree will inject global styles into the document.

Basic example of createGlobalStyle usage

This can be useful if (like 0x Tracker) you use a design framework such as Bootstrap and want to override some of the global styles without creating a suite of base components.

Your initial instinct may be to wrap each story in React.Fragment and include your GlobalStyle component. Whilst this would do the job, it’s tedious boilerplate that would need duplicating across every story and if you’re using an addon like addon-jsx will pollute the generated examples 🙅‍♂️ Fortunately there is a much cleaner way to achieve what we need…

Storybook provides a decorators API which allows us to decorate stories with additional functionality. These decorators can be applied on an individual story basis but more importantly they can be applied globally.

To apply a global decorator we need to modify our Storybook config file, typically located at .storybook/config.js with something like this:

Applying global styles to all of our stories

Voila! When the Storybook UI now tries to render a component it will first pass through our withGlobalStyles decorator and inject global styles before returning the original story content to the user 🙌