Creating a seamless integration of Material UI V5 ThemeProvider in Storybook V6 within the NX workspace involves a series

I am currently utilizing nx.dev as my monorepo setup with various React clients. With NX, I have centralized the configuration for Material Ui inside the lib folder.

The issue arises when I try to integrate Storybook within the mui folder. Unfortunately, the ThemeProvider does not apply, causing my custom palette settings to be ignored. I am unsure why Storybook is not recognizing the Themeprovider from MUI. Could this be related to NX or is it a separate issue?

It seems like there are compatibility challenges between React 18, Storybook 6, and MUI 5. However, there should be a solution as I have successfully built it before with lower versions and without using NX.

Within the lib folder, there is a mui folder containing a .storybook folder.

Main.js

const rootMain = require('../../../.storybook/main');

module.exports = {
  ...rootMain,

  core: { ...rootMain.core, builder: 'webpack5' },

  stories: [
    ...rootMain.stories,
    '../src/lib/**/*.stories.mdx',
    '../src/lib/**/*.stories.@(js|jsx|ts|tsx)',
  ],
  addons: [
    ...rootMain.addons,
    '@nrwl/react/plugins/storybook',
   
  ],
  webpackFinal: async (config, { configType }) => {
    // apply any global webpack configs that might have been specified in .storybook/main.js
    if (rootMain.webpackFinal) {
      config = await rootMain.webpackFinal(config, { configType });
    }

    // add your own webpack tweaks if needed

    return config;
  },
};

Preview.js

import React from 'react';
import { ThemeProvider, theme } from '../src';


export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

export const decorators = [
  (Story) => (
    <ThemeProvider theme={theme}>
      <Story />
    </ThemeProvider>
  ),
]; 

I also attempted the following in preview.js

import React from 'react'
import { addDecorator } from '@storybook/react'
import { ThemeProvider } from '../src'
import { theme } from '../src'


export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
}

addDecorator((story) => (
  <ThemeProvider theme={theme}>
    {story()}
  </ThemeProvider>
))

Inside the src folder of the lib folder, there is an index.ts file which includes:

export * from './theme';

export * from '@mui/material';

Theme.ts

const theme = createTheme({
  palette,
  spacing: [0, 4, 8, 16, 24, 32, 48, 56, 64, 80, 96],
  components: {
    ...Buttons,
  },
});

export default theme;

Answer №1

I have finally resolved that particular issue

react material-ui v5 theming not functioning properly with storybook.

This discovery has been incredibly beneficial to me.

import { ThemeProvider, theme } from '../src';
import { ThemeProvider as Emotion10ThemeProvider } from 'emotion-theming';

export const decorators = [
  (Story) => (
    <Emotion10ThemeProvider theme={theme}>
      <ThemeProvider theme={theme}>
          <Story />
      </ThemeProvider>
    </Emotion10ThemeProvider>
  ),
];

Answer №2

@maxfromgermany. I recently encountered a similar issue and managed to solve it using this code snippet. Simply insert the following code into your ".storybook/preview.js" file.

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/
    }
  }
}

import React from "react"

import { addDecorator } from "@storybook/react"
import { ThemeProvider } from "@mui/material/styles"

import { muiTheme } from "../src/config/mui-theme"

addDecorator((story) => <ThemeProvider theme={muiTheme}>{story()}</ThemeProvider>)

~ Storm In Talent

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

Hiding the initial parent SVG element in the list will also hide all subsequent SVG elements within each section, excluding the container

I encountered a strange issue with my code in the Next framework. When using getServerSideProps, I made a request to my api folder, which resulted in a simple JSON response. Everything seemed to be working fine. The content was displayed perfectly without ...

Encountering CORS Issue When Accessing Xero Node/Python SDK APIs within a React Application

While trying to fetch data from the Xero node SDK APIs in my React application, I am facing a CORS (Cross-Origin Resource Sharing) error. Even after setting up the necessary headers and permissions on both the client and server ends, the CORS policy remain ...

Error: The function channel.on cannot be recognized within the Twilio API

I am encountering an issue with a function in my ReactJS application that is responsible for initializing the Twilio services I am utilizing. It appears that the Twilio channels are not being accessed properly. Below is the snippet of code causing the prob ...

What's the best way to retrieve data on button click in Next.js?

I'm working on a web application that includes an input field and a button next to it. When the user clicks the button, I need to fetch data from the server. Initially, I tried using SWR for this functionality but I'm not entirely sure if SWR is ...

Increase the count if the item is already in the shopping cart - React

Is there a way to avoid adding the same product to the basket multiple times and instead just increment a counter? How can I effectively keep track of each item's count? this.state = { description: '', commaSalesPrice: '', ...

I am experiencing an issue where React Hook Form is not showing objects in the console upon submission

My goal is to use react-hook-form with two material UI text fields to gather data and display it in the console. However, when I click the submit button, nothing shows up in the console.log as expected. Here is my code: import React from 'react&apos ...

I am having trouble with data populating in an Array within the UseEffect hook in React

Within my useEffect function, I am populating two arrays, each containing two elements. However, only one element from each array is displaying on the page. https://i.stack.imgur.com/ZUeow.png This is the contents of the useEffect function: useEffect(( ...

utilize an arrow function as a component prop argument

Struggling to pass the outcome of handleRedirectUrl() function as a prop to ShortUrlField component. In need of assistance, unsure of the mistake I am making const handleRedirectUrl = () => { urlService .getShortenedUrl(urls.slice(-1)[0].shor ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Creating an array in ReactJS by mapping a JSON object: A step-by-step guide

I've got a JSON object that I need to parse and create two separate arrays. One array will contain the ART field data, while the other will store the SALIDA field values. Click here to see the JSON data For more information on ReactJS const DisplayT ...

The material UI tabs text is missing the ellipses due to a coding error

As a newcomer to web development, I am experimenting with adding an ellipsis to the span element within the tabs. <div class="MuiTabs-scroller MuiTabs-fixed" role="tablist" style="overflow: hidden;"> <div class="MuiTabs-flexContainer"> ...

I am looking for a way to distinguish between mandatory and non-mandatory input fields in React

I've encountered an issue with the borders of the text fields in my React project. Here's how I want the text fields to look: https://i.stack.imgur.com/MP6DG.png Currently, the borders appear straight in the browser even though I want them rou ...

Can one access non-static methods within React Navigation's navigationOptions?

Within my form, I am trying to position a submit button to the right of the header that triggers the same method as the submit button located at the bottom of the form. React Navigation necessitates the declaration of a static method named navigationOptio ...

The robots.txt of Websiteplanet does not specify a sitemap URL

This is how my robots.txt file is set up: User-Agent: * Disallow: /info/privacy Disallow: /info/cookies Allow: / Allow : /search/Jaén Allow : /search/Tarragona Allow : /search/Rioja Sitemap: https://www.alquileres.xyz/sitemap.xml However, when I verify t ...

The save feature becomes dysfunctional after switching to the Material-UI dependency in a React project

After integrating the Material-UI dependency into my ReactJS code, I encountered an issue where the "save" functionality no longer works properly. Previously, when editing a task in my simple Todo list app, the new name would be saved successfully. However ...

Modify the content of a post in the Gutenberg editor on Wordpress

Let me outline the steps I have taken so far: I have created multiple posts using Gutenberg, incorporating various types of blocks/elements I have also designed a page using Gutenberg One of the functionalities I added is a custom widget called "load-pos ...

Jenkins is causing the npm test to fail, whereas the test passes without any

Encountering Issue with npm test Below is the error message received: FAIL src/Tests/Workflow.test.js ● Test suite failed to run ENOENT: no such file or directory, mkdir '/tmp/jest_4df/jest-transform-cache-4e6d562894209be60da269aa86f9333c-d1 ...

Embed my React component within a personalized hook

Utilizing React 18, Material UI version 5, and nanostores version 0.7.4. I have developed a custom hook called useApi.tsx which sets up a new axios instance every time the hook is used. Within this hook, an interceptor has been implemented to capture error ...

Next.js allows for the implementation of unique global CSS styles for specific sets of components

We recently purchased a blog theme from ThemeForest with plans to integrate it into our web application. However, we have encountered an issue regarding the global CSS. Our web app already has its own set of global styles imported on the `_app` component. ...

Tips for sorting through mapped information using many selection choices in React

I have generated some sample data and I am looking to display it based on a selection made from a dropdown menu. The content to be displayed should closely match the selection made. For instance, if I choose the option 'java', then the system sh ...