Issue with Material UI styles not applied in component (alert: multiple occurrences of `@material-ui/styles`)

I have developed a standalone React component that utilizes the Material UI (4.8.3) library and have uploaded it to a private NPM package for use across various applications.

The standalone component project is functioning properly (tested using Storybook), but upon publishing and importing the component into a new React project (created with create-react-app), I am receiving the following warning:

It appears that there are multiple instances of `@material-ui/styles` initialized in this application. This may lead to theme propagation issues, broken class names, specificity issues, and unnecessary increase in application size.

The component is being rendered on the page as shown below, but the theming is not being applied:

https://i.sstatic.net/D2oxr.png

When clicked, the theming from the main React App is stripped off (notice the loss of color in the dark blue bar in the background behind the menu):

https://i.sstatic.net/04z4y.png

I am utilizing the Material UI `withStyles` feature to theme my component, which seems to be causing the issue since the main React app also uses this. However, this is the recommended styling approach. Does it seem like I need to somehow inherit a theme instance from the main host App?

The component project was generated using create-react-library and hence is employing Rollup (0.64.1) and babel (6.26.3).

Below is the code for the component:

import React, {Component} from 'react'
import { withStyles } from '@material-ui/core/styles'

const styles = theme => ({
    root: {
        fontSize: '14px',
    }
})

// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class MyComponent extends Component {

    render() {
        const { classes } = this.props

        return (
            <div className={classes.root}>Hello world</div>
        )
    }
}

export default withStyles(styles)(MyComponent)

After being published to an NPM package, the component is imported into the main app with the following code:

import React, { Component } from 'react'
import { MyComponent } from '@xxx/mycomponent'

const styles = theme => ({
  root: {
    display: "flex",
    flexGrow: 1
  }
});

// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Class
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class App extends Component {
  // 

  // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  render() {
    // 
    const { classes } = this.props;

    return (
      <div className={classes.root}>
        <MyComponent />
      </div>
    );
  }
}

export default withRouter(withStyles(styles)(App))

Answer №1

I encountered a similar issue, but I do not utilize StoryBook. Since this is the top search result on Google, I decided to share my experience here in case it can be of assistance to others.

Here is the resource I found on how to resolve the alert, although it did not work in my case. Executing npm dedupe had no effect, and modifying the configuration was not an option due to my use of create-react-app.

As a solution, I performed the following steps:

  1. Removed the @material-ui/styles dependency from package.json
  2. Executed npm i
  3. Updated all instances of
    import styles from '@material-ui/styles'
    to
    import styles from '@material-ui/core/styles'

Answer №2

Dealing with a similar setup, I encountered the same issue when trying to import components into a new project. Our team relies on webpack to compile the app that uses the component. To resolve the issue, I was advised to make a small tweak in my webpack configuration:

module.exports = {
  ...
  resolve: {
    alias: {
      "@material-ui/styles": require.resolve("@material-ui/styles")
    }
  }
}

Implementing this change worked like a charm for my situation.

For more information, you can visit: https://webpack.js.org/configuration/resolve/

Answer №3

Include @material-ui/styles in your storybook by linking it. To do this, execute the command npm link @material-ui/styles in your storybook, and then in your applications.

Answer №4

Consider installing the following package. It worked for me when I encountered a similar issue.

npm install @mui/material

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

The toggleDrawer() function in React Native's NavigationDrawer does not seem to be functioning properly

Within the header, there is a button that is meant to open and close the navigation drawer menu. When I invoked the following method from componentDidMount(), it successfully opened the menu: this.props.navigation.toggleDrawer(); However, when I clicked ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Unique backgrounds with varied images on each grid block

Hi there! I'm currently exploring options to display different images for each section of a grid I've put together: Take a look at the CSS I'm using: background-image: url("my_image.jpg"); background-size: 50px auto; float: right; height: ...

Determine which specific [SelectField] [DropDownMenu] triggered the onChange event

As I programmatically generate various SelectField and DropDownMenu components, I am facing the challenge of handling their onChange events with a single handler function. Unfortunately, I have not been able to find a way to determine which specific Sele ...

Shared items found in a pair of entities

This function currently returns the difference between two objects, but I need to modify it so that it returns the common objects instead. Any assistance on how to achieve this would be greatly appreciated. Array example: var array1 = [ { "Name": " ...

Issues with passing information from a child component to a parent component in a

Currently, I am developing a guessing game that involves questions and selection logic embedded in a component known as Questions. However, I am facing issues with App not being able to read the Questions code correctly. My objective is to have the state i ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Converting HTML content to L20N format after dynamically modifying the DOM

While working on my knockout based website, I decided to implement L20n to enhance the user experience. However, I encountered a few challenges along the way. One of the issues I faced was related to dynamically creating views. I was wondering how I could ...

Transforming a Shadertoy experiment into a customized Three.js playground on my local machine

I am currently working on a local shader sandbox project inspired by a Shadertoy created by lennyjpg. I have been referencing two Stack Overflow questions and answers (one, two) for help. The goal is to convert the Shadertoy code to use Three.js for a larg ...

Error: The function _this.props.startAddComponent cannot be found, resulting in a TypeError when attempting to utilize mapDispatchToProps

I've encountered a problem with the mapDispatchToProps function. It's not passing down my "startAddComponent" action as a prop. Here is the code for my component page: import React from 'react'; import {connect} from 'react-redux ...

Hide popup using HTML when clicking outside of it

Currently, I have implemented Bootstrap Popover with HTML content using the code snippet below. This code is based on the answer provided at . $(".song-status-link").popover({ html: true, placement: 'bottom', ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...

Having trouble getting custom Themes to apply in Material UI version 5

I meticulously followed the documentation to create a custom theme, but unfortunately, I'm not seeing any changes reflected in my UI. Both the primary and secondary colors remain the same as the default, despite my efforts. Additionally, the warning, ...

Creating a custom class implementation in JavaScript and initializing it with a constructor function

Perhaps there is a similar question out there, but I haven't come across it yet and I'm still facing an issue. Here's what I've tried: function createClass(obj) { const constructor = obj.constructor; constructor.prototype = obj; ...

How to iterate through an array in jQuery/JavaScript and create variables in each loop?

I've been puzzled for a while now as to why this code snippet doesn't work as intended: if (longest.length >= 3) { for ( var i = 0; i < longest.length-1; i++) { var $last[i] = longest[i].splice(-1).toString(); //if ( $( $la ...

`There is a lack of props validation in the react/prop-types``

As I set up my Next-React app on Netlify, I encountered an error in the deploy log: Netlify deploy log indicates: "Error: 'Component' is missing in props validation", "Error: 'pageProps' is missing in props validation" within my ./page ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

Using jQuery to duplicate elements by copying and pasting

I am facing a scenario where I need to dynamically create and manipulate a div element in my web application. The process involves appending the newly created div to another container upon clicking a button, followed by triggering a series of functions on ...

Creating a JavaScript function to imitate the pressing of the Enter

I am attempting to mimic the pressing of the Enter key using JavaScript within a specific TextArea. Below is the code I have written: function enter1() { var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = ...