Following an update, Storybook is failing to apply JSX styles

After upgrading my project from NextJS 10 to NextJS 12, everything is functioning normally except for Storybook, which is now missing its styles.

I utilize the styled-jsx library to create embedded css, implementing it in this way:

const SearchResult = ({ onClick, vehicle }: SearchResultProps): JSX.Element => {
  return (
    <div className="search-result" data-testid="search-result" onClick={onClick}>
      <style jsx>{styles}</style>
      ...
    </div>
  );
};

The generated styles look like

class="jsx-2615582530 search-result"
. Previously, before the update, there would also be an embedded style search-result.jsx-2615582530 within the produced storybook. However, post-update, although the jsx style names are present, the actual styles seem to have disappeared.

I updated from styled-jsx version 3.3.1 to 5.0.0 and moved up to NextJS 12.0.3. I did not make any changes to loaders or anything else. It’s possible that webpack may have been upgraded during the process.

Here's my configuration:

const webpack = require('webpack');

module.exports = ({ config }) => {
  // Fill in process.env on the client
  config.plugins.push(
    new webpack.DefinePlugin({
      'process.serializedEnv': {},
    })
  );

  // Sentry requires different packages for front and back end,
  // but in storybook we know it's always client side
  config.resolve.alias = {
    'sentry-alias': '@sentry/browser',
    '@/remoteConfig': './standardRemoteConfig',
  };

  config.module.rules.push({
    test: /\.md$/,
    loader: "raw-loader",
  }),

  config.externals = [...(config.externals || []), 'fs', 'net'];

  config.resolve.extensions.push('.md');

  config.resolve.fallback = {
    "https": false,
    "stream": false,
  };

  return config;
};

and here’s part of the main configuration:

module.exports = {
  core: {
    builder: 'webpack5',
  },
  stories: ['../stories/**/*.stories.tsx'],
  addons: [
    '@storybook/addon-actions',
    '@storybook/addon-links',
    '@storybook/addon-backgrounds',
    '@storybook/addon-knobs',
    '@storybook/addon-viewport',
    '@storybook/addon-a11y',
    'storybook-addon-paddings',
  ],
};

Additionally, when I include styles as

<style>{styles}</style>
without the jsx prop, they do appear in the resulting storybook output.

However, the text appears strangely:

When using the jsx attribute, the <style /> element is entirely absent from the final markup.

Any suggestions on how to resolve this issue?

Answer №1

A more recent version of styled-jsx now requires the following:

+import { StyleRegistry } from 'styled-jsx';

Additionally,

-export const decorators = [withPaddings, withRedux(), (story: Function) => <I18nextProvider i18n={i18n}>{story()}</I18nextProvider>]
+export const decorators = [(Story) => (
+  <StyleRegistry>
+    <Story />
+  </StyleRegistry>
), withPaddings, withRedux(), (story: Function) => <I18nextProvider i18n={i18n}>{story()}</I18nextProvider>]

With these changes, embedded jsx styles are once again visible.

Answer №2

If you happen to stumble upon this, the solution that worked for me was updating styled-jsx to version 5.0.4. This resolved the issue as we are using Next 12 and have styled-jsx specifically included in our dependencies.

Check your package.json file for styled-jsx and ensure it is at the correct version (I recommend >=5.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging both onmouseover and onmouseout for container expansion

My goal is to utilize JavaScript along with the HTML events "onmouseover" and "onmouseout" to create a dynamic container. Essentially, I want the container to act as simply a heading when the mouse is not hovering over it, but expand to display additional ...

What could be causing the error that keeps popping up when I attempt to create a Next app?

Trying to master Next.js has been a bit of a challenge for me. Every time I attempt to create an app, a network error pops up saying the request to https registry.npmjs.org/create-react-app failed due to connect ETIMEDOUT. It suggests that I may have a p ...

Logging with Nextjs server on production mode

I have encountered an issue with my Next.js 14 project that uses server-side rendering. I noticed that when I add console.log and Winston logger to my server components, the logs are displayed when I run npm run build. However, when I try to run npm run st ...

How to Align the Button Vertically with the TextField in React Material-UI

Utilizing the Material-UI library for React, I have been working on creating a simple form with the following design: https://i.stack.imgur.com/LY3ZN.png My challenge lies in aligning the button with the TextField element. Adjusting the margin-top proper ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

What is the best way to create a seamless background transition for buttons on a mobile device?

Currently, I am working on my random quote generator project and I am trying to make it so that when the button is touched on a mobile device, the background color becomes semi-transparent. Below is the code I am using: #loadQuote { position: fixed; w ...

Can Rollup be utilized solely for processing CSS files?

I am curious about whether Rollup can be used solely for processing CSS files, such as css, scss, less, etc. For example, if I have a file called index.css in my src folder (the entry folder) and want Rollup to process it in the dist folder (the output fol ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Using VML for background images in Outlook using HAML: A step-by-step guide

I am currently working on formatting an email digest using HAML and tables. My goal is to set a background-image to a table-cell in the email, but I've come to realize that Outlook requires VML in order to display a background-image correctly. After ...

The proper way to update MUI styles

click here to see an image I am looking to customize the background style in this code snippet: MuiAccordion: { styleOverrides: { root: { boxShadow: 'none', position: 'inherit', '& .Mui-expanded': ...

Adjust the color of error messages in shiny from red

Currently, I am in the process of developing a Shiny app that includes numerous plots. Whenever I adjust any input parameters, there is a brief moment where the plots do not display before they are rendered, accompanied by a prominently displayed red error ...

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

When attempting to utilize the dispatch function in a class-based component, an invalid hook call error may

I am a beginner with react-redux. I currently have this code that uses react, redux, and TypeScript. The code utilizes a class-based component and I am attempting to use dispatch to trigger an action to increment the value of counter. However, I encountere ...

The content within the flex box element is making the flex box element grow in size

I have set up a flex box container with 3 child divs inside, and I would like to maintain the same size ratio for all 3 (1:1:1). However, when I add text to the child divs, the ratios change to accommodate the overflow of text. For example: ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

Tips for implementing dynamic data in React applications

I have a collection of data consisting of various objects stored in an array (json file) that will be displayed using React. const Library = [ { name: "Star Wars" }, { name: "Harry Potter" }, ... ]; // Main App Component class App extends React.Componen ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...

Efficiently rendering web pages with Next.js

In my market application, I have a page that displays a list of products. Which rendering type would be the optimal choice for this scenario? Will Static Generation update the list when the page is refreshed? ...

CSS: What is causing my three columns to divide?

I am encountering CSS issues while attempting to develop a React app using Next.js. Here is the content of my home.module.css: .grid_container { /* display: grid; */ /* grid-template-columns: auto auto auto; */ /* column-count: 3; align-items: fle ...

Bypassing the email verification step during the registration process in Supabase using auth-helpers for Next.js and the 'pages' folder

Initially, I set up client-side authentication in my NextJS application using the supabase-js library. However, I am now transitioning to using the auth-helpers-nextjs library for authentication so that I can access the User server-side (specifically for s ...