Introduction
Have you encountered a frustrating issue with Storybook where your custom fonts are not showing up? You’ve come to the right place! In this guide, we’ll dive into the problem and provide you with step-by-step solutions to get your fonts displaying correctly in Storybook. Let’s explore this font-related mystery together!
Understanding the Material UI Theme Setup
To set the stage, let’s first understand the Material UI theme setup in your application. You have a Material UI theme with custom fonts defined in the typography section. The fonts are applied to different elements, such as headings and buttons, to create a consistent visual experience. However, despite everything appearing fine in the application, Storybook seems to be the one holding back your custom fonts.
Investigating the Storybook Configuration
To solve the mystery, we need to examine the Storybook configuration. Storybook allows you to showcase and test UI components in isolation, but sometimes it doesn’t play nicely with custom fonts. You’ve tried importing local CSS and even adding @font-face
declarations directly in your component, but the fonts still refuse to show up in Storybook.
Potential Solutions
-
Separate CSS File for Fonts:
- Create a separate CSS file dedicated to defining
@font-face
for your custom fonts. - In your Storybook configuration, specifically in the file
preview-head.html
, add a<link>
tag pointing to the CSS file containing your font definitions.
- Create a separate CSS file dedicated to defining
-
Check for Shadow DOM Restrictions:
- If your fonts are not local and are loaded from an external source, the issue might be related to Shadow DOM restrictions.
- Try adding the
@font-face
declarations in the top-level DOM rather than within the component’s shadow DOM boundaries.
Step-by-Step Guide
Now, let’s dive into the step-by-step guide to fix the issue:
Step 1: Create a Separate CSS File
- Create a new CSS file, let’s call it
fonts.css
, to contain the@font-face
definitions. - Place this file in a location accessible to your Storybook configuration.
Step 2: Add Link to preview-head.html
- Locate the
preview-head.html
file within your Storybook configuration directory. - Inside this file, add the following line to include the CSS file for your fonts:htmlCopy code
<link rel="stylesheet" href="./fonts/fonts.css" />
Step 3: Verify and Restart Storybook
- After adding the link to the
preview-head.html
file, save the changes. - Restart your Storybook server to apply the updated configuration.
Conclusion
By following these steps, you should be able to resolve the issue of your custom fonts not showing up in Storybook. Remember to create a separate CSS file for your @font-face
declarations and include it in the preview-head.html
file. With these changes in place, your Storybook components should inherit the custom fonts correctly, providing a consistent visual experience.