Unable to decipher Material UI class names

I am experimenting with a React app using Material UI to explore different features. I'm attempting to customize the components following the original documentation, but making some changes as I am using classes instead of hooks. However, I keep encountering an error: Cannot read property 'root' of undefined. It seems like there are no "classes" in my props, and I'm not sure why.

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

import "./Product.css";

const useStyles = (theme) => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
  },
});

export class Product extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isExpanded: false,
    };
  }

  render() {
    const { isExpanded } = this.state;
    const { classes } = this.props;
    debugger;
    return (
      <Container maxWidth="lg" className="full-container">
        <div className={classes.root}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Paper className={classes.paper}>xs=12</Paper>
            </Grid>
          </Grid>
        </div>
        <Accordion
          expanded={isExpanded}
          onChange={() => this.setState({ isExpanded: !isExpanded })}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel1bh-content"
            id="panel1bh-header"
          >
            <Typography className="heading">General settings</Typography>
            <Typography className="secondaryHeading">
              I am an accordion
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Typography>
              Nulla facilisi. Phasellus sollicitudin nulla et quam mattis
              feugiat. Aliquam eget maximus est, id dignissim quam.
            </Typography>
          </AccordionDetails>
        </Accordion>
      </Container>
    );
  }
}

export default withStyles(useStyles)(Product);

Thank you!

Answer №1

This piece of component code is perfectly fine.
Within this file, you are exporting two items: one is an export named App class, and the other is a default export using a higher-order component withStyles. To make use of useStyles, you must import the default export from this file. It seems like you are importing the component incorrectly with import {App} from './App', which is causing the error. Make sure to import the default export properly like this, import App from './App'

Answer №2

I have provided the working code below:

https://codesandbox.io/s/material-demo-forked-jgfqn?fontsize=14&hidenavigation=1&theme=dark

If you are facing issues with imports, please update your question with the specific imports you are using.

In the code snippet below, I replaced the icon in the accordion and included the necessary imports:

import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import {
  Container,
  Grid,
  Accordion,
  AccordionSummary,
  Typography,
  AccordionDetails,
  Paper
} from "@material-ui/core";

import { ExpandMoreOutlined } from "@material-ui/icons";

The functioning document is displayed below:

import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import {
  Container,
  Grid,
  Accordion,
  AccordionSummary,
  Typography,
  AccordionDetails,
  Paper
} from "@material-ui/core";

import { ExpandMoreOutlined } from "@material-ui/icons";

const styles = (theme) => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary
  }
});

export class Product extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isExpanded: false
    };
  }

  render() {
    const { isExpanded } = this.state;
    const { classes } = this.props;
    debugger;
    return (
      <Container maxWidth="lg" className="full-container">
        <div className={classes.root}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <Paper className={classes.paper}>xs=12</Paper>
            </Grid>
          </Grid>
        </div>
        <Accordion
          expanded={isExpanded}
          onChange={() => this.setState({ isExpanded: !isExpanded })}
        >
          <AccordionSummary
            expandIcon={<ExpandMoreOutlined />}
            aria-controls="panel1bh-content"
            id="panel1bh-header"
          >
            <Typography className="heading">General settings</Typography>
            <Typography className="secondaryHeading">
              I am an accordion
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Typography>
              Nulla facilisi. Phasellus sollicitudin nulla et quam mattis
              feugiat. Aliquam eget maximus est, id dignissim quam.
            </Typography>
          </AccordionDetails>
        </Accordion>
      </Container>
    );
  }
}

export default withStyles(styles)(Product);


Answer №3

By using your code, I have successfully created a functional sandbox environment. You can access it here: https://codesandbox.io/s/jolly-cray-sy4tk?file=/demo.js:27-499. It seems like the issue might be related to how you are importing other MUI components, as that was the only area I made adjustments to (due to incomplete import information provided).

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

Website route organization tool

Seeking assistance with implementing a route planning feature on my website. The user should be presented with multiple route options upon entering their origin and destination. Take a look at this reference site for inspiration: Any help would be great ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...

Automatically calculate the multiplication of a number by 10 in React JS within the State

In this scenario, I am looking for assistance in creating a functionality where the user can adjust numbers in an input box and see the result of that number multiplied by 10 in a nearby span element. However, I am encountering issues with fetching the des ...

CSS and JavaScript dropdown malfunctioning due to a position swap in internal CSS

This example demonstrates functionality .c1 { background-color:red; position:relative; } .c2 { background-color:blue; position:absolute; height:50px; width:100px; display:none;} .show { display:block; } <body> <button ...

Tips for adding a border radius to dialogue material ui components

How do I apply a border radius to a Material UI dialog? The image represents a popup dialog that acts as a button, and I want to style it with rounded corners. I've tried setting the borderRadius in the sx property, but it's not working. Here&ap ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Element not producing output via Autocomplete from mui/material package

My challenge involves handling an array of states within the Autocomplete component. Once a state is selected, a corresponding component needs to be rendered based on the selection. However, despite successful state selection in the code, nothing is being ...

Is it possible to stack images on top of each other on a webpage?

I'm looking to create a dress-up game website where users can click on different accessories to layer them on top of each other. It's a bit tricky to explain, but I've found some examples that demonstrate what I have in mind: This site is ...

Warning: Ensure each item in a list has a unique key when

I'm relatively new to react and encountering a problem that's stumping me. Here is the react component I'm working with: import React from 'react'; import Header from './Header'; import ContestPreview from './Contes ...

Two problems encountered with the scroll bar feature on a tabular display

Have 2 inquiries about the table displayed below: Question 1: The height of the table is set to 500px, but I am puzzled by the fact that it seems like the content below, which is not part of the table, appears within the table due to the scroll bar exten ...

Issue with using styled API for keyframe animation in MUI 5 - not functioning as expected

I am attempting to add animations to a button when hovered by using styled from MUI 5, but unfortunately, it is not working as expected. I have looked for guidance and inspiration from: How to apply custom animation effect @keyframes in MaterialUI using m ...

What is the best way to keep a dropdown list menu next to the selected dropdown button as the user scrolls?

I recently encountered a problem similar to the one on this page within my App. Upon selecting the drop-down list, the corresponding menu opens as expected. However, when the user scrolls down the page, the drop-down menu remains in its original position. ...

Error occurred when attempting to fetch data from a nested JSON object in React/Next.JS

Having trouble retrieving data from my API and encountering this error message. I suspect it may be related to the JSON structure. Interestingly, when using a different URL with nested arrays, it works fine. However, my current data is not cooperating. Any ...

The words run out before the paper does. Keep reading for more details

While updating the CSS on my blog, I ran into an issue where the text in my posts is not extending all the way to the end. To see what I'm experiencing, check out this image- I really need the text to align properly and reach the full width of the p ...

Troubleshooting Display Problems when Switching Bootstrap Themes in ASP.NET MVC

I recently made changes to my MVC project by switching the default Bootstrap theme to Bootswatch - Cosmos. However, I am facing an issue with the Navbar as shown in the image below: View Header Display Issue Image Initially, I was using Bootstrap 3.0 and ...

Unable to iterate through nested arrays in Contentful mapping

I am facing an issue while trying to map further into the array after successfully retrieving data from Contentful. The error message field.fields.map is not a function keeps popping up and I can't figure out what I'm doing wrong. export defau ...