DEV Community

Cover image for How to Fix Storybook Broken Styles When Using Styled-JSX
Jean Gérard Bousiquot for JGB Solutions

Posted on • Updated on

How to Fix Storybook Broken Styles When Using Styled-JSX

Recently I've been tasked to fix a styling issue on a Next.js + Storybook project. Most of the React components where displaying fine when used inside of a Next.js page but wouldn't in Storybook. That was frustrating. The fix is to include the Babel and Webpack configs for Storybook within the .storybook directory. Here is how I did it:

First install babel-loader and babel-plugin-react-require using npm or yarn if they were not already installed. Then create a new file named .babelrc inside .storybook if it doesn't exist and paste the following:

{
  "presets": [
    "@babel/preset-react"
  ],
  "plugins": [
    [
      "styled-jsx/babel",
      {
        "sourceMaps": true
      }
    ],
    "react-require"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Create a second file named webpack.config.js at the same location with the following content:

const path = require('path');

module.exports = {
  module: {
    rules: [
      {
        test: /\.(jsx?|css)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        include: path.resolve(__dirname, '../'),
        use: [
          {
            loader: require('styled-jsx/webpack').loader,
          },
        ],
      },
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

This is all we need to get it working. Now run npm run storybook or yarn storybook to see it working. Enjoy!

Discussion (1)

Collapse
juliandelsanto profile image
Julian Delsanto

Hello, I was testing the stories shown in storybook but without the corresponding styles