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

Looking to incorporate content from an external website onto my own site

I have experimented with various types of HTML tags such as iframe, embed, and object to display external websites. Some of them load successfully, while others do not. After researching my issue on Google, I discovered that "For security reasons, some si ...

Tips for defining a relative path in the base URL with AngularJS

Encountering an issue with AngularJS routes related to file paths. The folder structure is as follows: js -> Angular -> css -> Bootstrap -> index.html Routes work fine when hosted on a server like IIS. However, copying and pasting the direct ...

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

Increase performance by minimizing unnecessary component re-renders in Next.js using memoization

I am currently exploring the behavior of React within Next.js. I have an index.js page that displays one component Homecard three times and a button that increments a value. Each time I click on the button, all Homecard components are re-rendered. index. ...

What are the reasons for not utilizing JSS to load Roboto font in material-ui library?

Why does Material-UI rely on the "typeface-roboto" CSS module to load the Roboto font, even though they typically use JSS for styling components? Does this mix of JSS and CSS contradict their usual approach? ...

Issue with applying fontFamily in React / Next.js 9

Issue Description I'm facing an issue with my Next.js application where I am unable to change the font family of a <p> element using in-line styles. Oddly, when I attempt to apply a color: 'red' style, it works without any problems. ...

What causes the iframe to protrude beyond the bottom of the page when set to 100% height?

I am facing an issue with an iframe on my website that is contained within a div. I have specified both to have a height of 100%, and I am using the blueprint framework, hence applying the class span-12 last. Despite these settings, a scroll bar still appe ...

React JS - CORS error persists despite implementing cors settings

Currently utilizing Express and ReactJS Express Code: const Express = require('express'); const PORT = 5000; const cors = require('cors'); const server = Express(); server.use(cors()); // CORS added here server.get('/users&ap ...

How can you prompt a component again in React Native after a specified number of days have passed?

I am currently working on a component that requests app permissions from the user. This component gives the user the option to either accept the permissions or choose "Later". If the user selects "Later", I want the component to prompt again after specific ...

The pseudo right arrow is failing to display in the vertical center

My pseudo right arrow is not displaying vertically centered within the .nav-link class. Can anyone suggest how I can achieve vertical alignment for my right arrow in an <a> tag? I have already attempted using top:50% but it did not work. Here is th ...

Retain the jQuery dropdown menu in an open state while navigating to a different webpage on the

I am encountering an issue with a drop-down menu on my website. Whenever I click on a submenu link, the new page opens but the menu automatically closes. However, I want the active menu to remain open even on the new page. To solve this problem, I believe ...

I'm having trouble installing node-sass and encountering an error. Can anyone offer advice on how to resolve this issue?

Encountering an error while trying to install node-sass, can someone assist me in resolving this issue? npm ERR! code EPERM npm ERR! syscall rename npm ERR! path C:\Users\deepe\OneDrive\Documents\Yajnaseni\POC\language&bs ...

The latest release of Next JS 13 is experiencing issues with Next Auth functionality

I need assistance. Ever since I started using the Next 13 app directory, it's been quite challenging. Most of the code that worked on the previous version is not compatible with this one, including Next Auth. I'm trying to connect my Firebase to ...

Is it possible to nest CSS Variables within CSS Variable names?

Is it feasible to embed a CSS Variable inside another CSS variable's name or perform a similar action like this: :root { --color-1: red; --index: 1; } span { color: var(--color-var(--index)) } ...

Emphasize multiple anchor points

I am looking to highlight two sections of a page simultaneously. Here is what I currently have: <li class="langLI" style="list-style-type:none"><a href="/non-discrimination-and-language-assistance##French">| French Creole</a></li> ...

Having trouble sending Props between components within a specific route as I keep receiving undefined values

Here is the code for the initial component where I am sending props: const DeveloperCard = ({dev}) => { return ( <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}> <Button variant="primary">Learn More</Butt ...

The text does not automatically move to the next line

How can I make the content in this form section wrap to the next line in a list-item and overlap the width of the div content? The second line, particularly where it mentions Security Question two This is my HTML & CSS: <ul class="o-pf-list o-pf- ...

Add a class to alternate elements when mapping over data in React

Check out the code snippet below: <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4"> {status === "success" && delve(data, "restaurants") && data.r ...

The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/ My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine. I was creating my own custom image viewer, and everything was ...

Resizing the window causes divs to be positioned relative to the image (almost functional)

In my coding project, I've encountered a situation where I have 3 "pins" positioned within a div called #outerdiv. This div has a background-image and the pins are supposed to remain in the same spot on the background image no matter how the window is ...